如何在dart中的函数外使用布尔值



我已经初始化了bool变量,然后创建一个函数并将其添加到我的init状态,这样应用程序一加载就会获取值。但它没有从函数中获得值,而是不断地获得初始化值

bool  hasInternet = false;
void initialization() async {
hasInternet = await InternetConnectionChecker().hasConnection;
print('ready in 3...');
await Future.delayed(const Duration(seconds: 1));
print('ready in 2...');
await Future.delayed(const Duration(seconds: 1));
print('ready in 1...');
await Future.delayed(const Duration(seconds: 1));
print('go!');
FlutterNativeSplash.remove();

}

hasInternet是我想在我的小部件中使用的变量

在statefulwidget中,在调用setState((({}(应用变量更改之前,您需要更新小部件的状态

问题是,您需要等待您的小部件构建完成,然后才能调用新的重建来应用更改。为此,我们在小部件init中包含了一个WidgetsBinding.instance.addPostFrameCallback,以便在小部件构建后调用您的函数,以防出现错误。

如果这是你在每个页面中进行的检查,并且你不介意反复调用或复制相同的代码,那么你可以使用statefulwidget使用以下示例,否则我建议你使用像Provider这样的状态管理包,它会通知应用程序中的每个小部件你定义的变量更改;

希望能有所帮助:

class YellowBird extends StatefulWidget {
const YellowBird({Key? key}) : super(key: key);
@override
State<YellowBird> createState() => _YellowBirdState();
}
class _YellowBirdState extends State<YellowBird> {
bool hasInternet = false;
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) => initialization());
}
Future initialization() async {
hasInternet = await InternetConnectionChecker().hasConnection;
print('ready in 3...');
await Future.delayed(const Duration(seconds: 1));
print('ready in 2...');
await Future.delayed(const Duration(seconds: 1));
print('ready in 1...');
await Future.delayed(const Duration(seconds: 1));
print('go!');
FlutterNativeSplash.remove();
setState(() {});
}
@override
Widget build(BuildContext context) {
return Text("Has Internet: $hasInternet");
}
}
bool  hasInternet = false;

void initState() {
checkInternt();
print('ready in 3...');
await Future.delayed(const Duration(seconds: 1));
print('ready in 2...');
await Future.delayed(const Duration(seconds: 1));
print('ready in 1...');
await Future.delayed(const Duration(seconds: 1));
print('go!');
FlutterNativeSplash.remove();

}
checkInternet()async{
hasInternet = await InternetConnectionChecker().hasConnection;
}

以这种方式使用它会起作用。谢谢

当我们需要考虑UI更新时,处理像provider/riverpod/block这样的状态管理会很好。但目前,您可以选择ValueNotifier。把它放在课堂之外公开,

final ValueNotifier<bool> hasInternet = ValueNotifier(false);

更改其值

hasInternet.value = true;

要在值更改时重新生成小部件,请使用ValueListenableBuilder

ValueListenableBuilder<bool>(
valueListenable: hasInternet,
builder: (context, value, child) {
return Text("hasInternet $value");
},
),

您可以像hasInternet.value一样收听更改。

关于ValueNotifierValueListenableBuilder的更多信息

最新更新