我有這個 StatefulWidget,它應該根據條件從 MySQL 資料庫檢索資料並將這些檢索到的值添加到數組中,以便我可以使用數組值顯示在 ListView 上。我的問題是,有時當陣列 (_fileValues
) 和 _custUsername
變數為空或未更新時,不會引發例外狀況。
這是我的有狀態小工具 (main.dart
)
String? _custUsername; List<String> _fileValues = <String>[]; class cakeLogin extends StatefulWidget { @override cakeLoginPageMain createState() => cakeLoginPageMain(); } class cakeLoginPageMain extends State<cakeLogin> { String? _CustEmailInit; BuildContext? loginContext; List<String> _fileNameStores = <String>[]; void callData() { // @ Get username based on user email and assign it to _custUsername variable UsernameGetter().Connection(_CustEmailInit!).then((UsernameValue) { _custUsername = UsernameValue!; }); // @ Get item names based on the user username (_custUsername) and add them into // _fileNameStores NameGetter().Connection(_custUsername).then((NamesValues) { for(var _nameItems in NamesValues) { setState(() { _fileNameStores.add(_nameItems); }); } }); // @ Remove duplicates value and add them into main list (_fileValues) var _removeDuplicates = _fileNameStores.toSet().toList(); for(var item in _removeNamesDupes) { setState(() { _fileValues.add(item); }); } } @override Widget build(BuildContext context) { final _emailController = TextEditingController(); return Scaffold( appBar: AppBar( title: Text("Login to App", style: TextStyle( fontSize: 18, color: setupFontCol, fontWeight: FontWeight.bold )), backgroundColor: setupThemeBar, centerTitle: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ) ), backgroundColor: setupMainTheme, body: Padding( padding: EdgeInsets.all(20), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextFormField( controller: _emailController, style: TextStyle(color: Color.fromARGB(255, 214, 213, 213)), decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), filled: true, hintStyle: TextStyle(color: Color.fromARGB(255, 197, 197, 197)), hintText: "Enter your email", fillColor: setupThemeBar ), ), SizedBox(height: 18), SizedBox(height: 25), SizedBox( height: 45, width: 500, child: ElevatedButton( style: ElevatedButton.styleFrom( primary: setupFontCol, onPrimary: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ) ), onPressed: () { var _CustEmail = _emailController.text; if(_CustEmail.contains("@gmail.com") || _CustEmail.contains("@email.com")) { if(_CustEmail != "") { _CustEmailInit = _CustEmail; loginContext = context; _isFromLogin = true; _fileValues.clear(); callData(); } else { alertDialog("Please enter your email address",context); } } else { alertDialog("Email address is not valid",context); } }, //color: setupFontCol, child: Text("Login", style: TextStyle( color: Colors.white, fontWeight: FontWeight.normal, fontSize: 14, )) ), ), ], ), ), ); } }
UsernameGetter
類別(此類將根據文字欄位輸入中的電子郵件從資料庫表中檢索使用者使用者名稱)
當我從UsernameGetter
類別列印_usernameDetected
類別時,它會傳回傳回字串的更新版本,但是當我將_custUsername
# 指派給 UsernameValue
從main.dart
時,它不會更新,有時會傳回null值。
import 'package:mysql_client/mysql_client.dart'; import 'dart:convert'; import 'dart:ffi'; import 'dart:typed_data'; import 'package:signuppage/main.dart' as main; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class UsernameGetter { Future<String> Connection(String _custEmail) async { final conn = await MySQLConnection.createConnection( host: "", port: , userName: "", password: "", databaseName: "", ); await conn.connect(); var _getUsernameQue = await conn.execute("SELECT CUST_USERNAME FROM information WHERE CUST_EMAIL = :email", { "email": _custEmail }); String? _usernameDetected; for(final _rowsOfEmail in _getUsernameQue.rows) { _usernameDetected = _rowsOfEmail.assoc()['CUST_USERNAME']!; } return await _usernameDetected!; } }
NameGetter
類別(檢索儲存在文字列中的使用者項目名稱)
對於 NameGetter
類,與 UsernameGetter
發生相同的情況。當我從 main.dart
檢索值並將值加到 _fileValues
列表中時,有時該值為空,有時該值未更新。
import 'package:mysql_client/mysql_client.dart'; import 'dart:convert'; import 'dart:ffi'; import 'dart:typed_data'; import 'package:signuppage/main.dart' as main; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class NameGetter { Future<List<String>> Connection(String _custUsername) async { final conn = await MySQLConnection.createConnection( host: "", port: , userName: "", password: "", databaseName: "", ); await conn.connect(); var _getItemNames= await conn.execute("SELECT ITEM_NAMES FROM item_details WHERE CUST_USERNAME = :username", { "username": _custUsername }); List<String>? _itemNamesValues= <String>[]; for(var _rowsOfItemNames in _getItemNames.rows) { var _retrieveNames = await _rowsOfItemNames.assoc()['ITEM_NAMES']!; _itemNamesValues.add(_retrieveNames); } return await _itemNamesValues; } }
我不確定我的錯誤在哪裡,但我很確定我犯了很多錯誤,我需要有人幫我解決。特別是關於為什麼列表和變數沒有更新/有時是空的。
參考連結:
Flutter ListView 未更新
我在 flutter 中的列表沒有更新程式碼中的問題
為什麼變數值在flutter中不刷新?
P粉5216974192024-04-02 09:09:07
callData()
方法的精簡版本如下:
var foo; void callData() { someAsyncFunction().then( ... foo = value ... ); anotherAsyncFunction(foo).then( ... ); }
如前所述,anotherAsyncFunction(foo)
在someAsyncFunction()
之後、then()
之前 立即呼叫> 分配foo
的值。
您可以透過有策略地插入 print()
語句來親自觀察此行為。
在底層,Future.then()
和 async
/await
是同一件事。然而,當使用async
/await
時,人們通常更容易推斷非同步程式碼的行為,因為這樣它讀起來就像順序執行的程式碼。
雖然您可以使用其中任何一個,但我建議您轉向 async
/await
以使程式碼在閱讀時更容易理解。
以下是如何重構 callData()
的一個範例:
FuturecallData() async { // @ Get username based on user email and assign it to _custUsername variable var custUsername = await UsernameGetter().Connection(_CustEmailInit!); // @ Get item names based on the user username (_custUsername) and add them into // _fileNameStores var namesValues = await NameGetter().Connection(custUsername); setState(() { _fileNameStores.addAll(namesValues); // @ Remove duplicates value and add them into main list (_fileValues) _fileValues.addAll(_fileNameStores.toSet()); }); }
這樣寫,很明顯 custUsername
是在呼叫 NameGetter().Connection(custUsername)
之前分配的。
請務必通讀非同步程式設計:futures、async、await。