gpt4 book ai didi

flutter - Flutter 上的有状态小部件中未显示文本

转载 作者:行者123 更新时间:2023-12-03 03:13:59 25 4
gpt4 key购买 nike

我正在尝试创建一个非常简单的应用程序,当单击中心小部件时,会显示列表中的元素。

这是我的代码:

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(
MaterialApp(home: MyApp()),
);

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Welcome to Flutter'),
),
body: Center(),
),
);
}
}

class picker extends StatefulWidget {
@override
_pickerState createState() => _pickerState();
}

class _pickerState extends State<picker> {
List yourList = ["Yes", "No", "Maybe"];
int randomIndex;

_pickerState() {
int randomIndex = Random().nextInt(yourList.length);
}

@override
Widget build(BuildContext context) {
return Center(
child: TextButton(
onPressed: () {
setState(() {
print(yourList[randomIndex]);
});
},
child: Text('$randomIndex'),
),
);
}
}

没有显示任何错误,但与此同时,我的目标没有达到,因为没有显示任何文本,即使我添加了此代码 print(yourList[randomIndex]);,终端也没有打印任何内容。如何显示文本并显示打印

enter image description here

最佳答案

另一种解决方案是设置

randomIndex = Random().nextInt(yourList.length);

在 setState(() { 如下所示。

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(
MaterialApp(home: MyApp()),
);

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Welcome to Flutter'),
),
body: picker(),
),
);
}
}

class picker extends StatefulWidget {
@override
_pickerState createState() => _pickerState();
}

class _pickerState extends State<picker> {
List yourList = ["Yes", "No", "Maybe"];
int randomIndex = 0;

@override
Widget build(BuildContext context) {
return Center(
child: TextButton(
onPressed: () {
setState(() {
randomIndex = Random().nextInt(yourList.length);
});
},
child: Text(yourList[randomIndex]),
),
);
}
}

要获得起始文本,需要在单独的函数中取出 setState,例如:

class _pickerState extends State<picker> {
List yourList = ["Yes", "No", "Maybe"];
String buttonText = "Initial Text";
int randomIndex = 0;

void _newRandomIndex() {
setState(() {
randomIndex = Random().nextInt(yourList.length);
buttonText = yourList[randomIndex];
});
}

@override
Widget build(BuildContext context) {
return Center(
child: TextButton(
onPressed: _newRandomIndex,
child: Text(buttonText),
),
);
}
}

关于flutter - Flutter 上的有状态小部件中未显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64451897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com