Setstate 在小部件列表中不起作用
Posted
技术标签:
【中文标题】Setstate 在小部件列表中不起作用【英文标题】:Setstate is not working inside list of widgets flutter 【发布时间】:2021-03-08 18:56:25 【问题描述】:我的问题是我的 列表的凸起按钮 不改变位置 ontap 停留在小部件列表中时 请帮帮我 并告诉我该代码有什么问题
class Sticker extends
StatefulWidget
Sticker(Key key) :
super(key: key);
@override
_StickerState
createState() => _
StickerState();
class _StickerState extends
State<Sticker>
Offset position =
Offset(50, 100);
List<Widget> list = [];
@override
Widget build(BuildContext
context)
return Container(
child: Stack(
children: [
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
),
Positioned(
left: 50,
top: 50,
child:
RaisedButton(
onPressed: ()
setState(
()
list.add(
Positioned(
left: position.dx,
top: position.dy,
child: RaisedButton(
onPressed: ()
setState(() => position = Offset(50, 150));
,
),
),
);
,
);
,
),
),
...list
],
),
);
我希望在我停留在列表中的同时点击它后我提出的改变位置 请帮我解决这个问题控制台没有错误
【问题讨论】:
【参考方案1】:您可以在下面复制粘贴运行完整代码
你可以使用StatefulBuilder
list.add(StatefulBuilder(
builder: (BuildContext context, StateSetter setState)
return Positioned(
工作演示
完整代码
import 'package:flutter/material.dart';
class Sticker extends StatefulWidget
Sticker(Key key) : super(key: key);
@override
_StickerState createState() => _StickerState();
class _StickerState extends State<Sticker>
Offset position = Offset(50, 100);
List<Widget> list = [];
@override
Widget build(BuildContext context)
print("build list.length $list.length");
return Container(
child: Stack(
children: [
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
),
Positioned(
left: 50,
top: 50,
child: RaisedButton(
onPressed: ()
setState(
()
list.add(StatefulBuilder(
builder: (BuildContext context, StateSetter setState)
return Positioned(
left: position.dx,
top: position.dy,
child: RaisedButton(
onPressed: ()
setState(()
position = Offset(50, 150);
);
,
),
);
));
,
);
,
),
),
...list
],
),
);
void main()
runApp(MyApp());
class MyApp extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
class MyHomePage extends StatefulWidget
MyHomePage(Key key, this.title) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
class _MyHomePageState extends State<MyHomePage>
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Sticker(),
);
【讨论】:
嘿,你能回答这个***.com/questions/65058620/…【参考方案2】:我认为您必须为列表中的每个按钮创建一个位置元素
List<Offset> position = Offset();
setState(() => position.add(Offset(50,150)));
【讨论】:
以上是关于Setstate 在小部件列表中不起作用的主要内容,如果未能解决你的问题,请参考以下文章
isPlaceholder 修饰符不可用且在小部件工具包 + SwiftUI 中不起作用
setState 在 setInterval 中不起作用 [重复]