我使用Modal底部工作表作为我的下拉列表,但是当我从底部工作表通过Navigator.pop()返回时,我无法弄清楚如何更新我的状态。显然,Modal类不支持setState。我很乐意接受任何人可以为这个问题提供任何帮助。除了selectedlang更新文本之外的所有内容都可以使用。应用程序设置为实际lang确实只更改文本未更新以向用户显示。
import 'package:flutter/material.dart';
import 'splash.dart' show lang;
import 'package:shared_preferences/shared_preferences.dart';
String selectedlang;
class LangSelect extends StatefulWidget {
@override
State<StatefulWidget> createState() => _LangSelectState();
}
class _LangSelectState extends State<LangSelect> {
void setLangDefault() {
selectedlang = "English";
lang = 'en';
}
void initState() {
super.initState();
setLangDefault();
}
Modal modal = Modal();
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: WillPopScope(
onWillPop: () async {
Future.value(false);
},
child: Column(
children: <Widget>[
Image.asset('assets/splash_logo.jpg'),
Center(
child: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Text('Welcome',
style:
TextStyle(fontSize: 40, fontWeight: FontWeight.bold)),
Text(''),
Text(''),
Text(
"Select a language.",
style: TextStyle(fontStyle: FontStyle.italic),
),
Text(''),
Container(
width: 120,
height: 30,
decoration: BoxDecoration(
color: Colors.grey[300],
border: Border.all(
color: Colors.black,
width: 1,
style: BorderStyle.solid),
borderRadius: BorderRadius.all(Radius.circular(20))),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(selectedlang),
IconButton(
padding: EdgeInsets.fromLTRB(25, 2, 2, 2),
icon: Icon(Icons.arrow_drop_down),
onPressed: () => modal.mainBottomSheet(context),
)
],
))
],
)),
],
),
));
}
}
class Modal {
mainBottomSheet(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_createTile(context, 'English', _action1),
_createTile(context, 'Español', _action2),
],
);
});
}
ListTile _createTile(BuildContext context, String name, Function action) {
return ListTile(
title: Text(
name,
textAlign: TextAlign.center,
),
onTap: () {
Navigator.pop(context);
action();
},
);
}
_action1() {
lang = 'en';
selectedlang = "English";
print(lang);
}
_action2() {
lang = 'sp';
selectedlang = "Español";
print(lang);
}
}
我通过简单地从调用它的Modal类中删除mainBottomSheet来解决这个问题,就像onPressed()=> void一样。然后我能够将我的setState放入我的行动中。