Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何在颤振中更新ModalBottomSheet的状态?_Flutter - Fatal编程技术网

Flutter 如何在颤振中更新ModalBottomSheet的状态?

Flutter 如何在颤振中更新ModalBottomSheet的状态?,flutter,Flutter,这段代码非常简单:显示一个模式的底部板材,当用户单击按钮时,板材的高度会增加10 但什么也没发生。实际上,只有当用户用手指“滑动”底部工作表时,它才会更新其大小(我相信滑动会导致工作表上出现内部设置状态) 我的问题是:如何调用ModalBottomSheet的更新状态 showModalBottomSheet( context: context, builder: (context) { return Container( height: height

这段代码非常简单:显示一个模式的底部板材,当用户单击按钮时,板材的高度会增加10

但什么也没发生。实际上,只有当用户用手指“滑动”底部工作表时,它才会更新其大小(我相信滑动会导致工作表上出现内部设置状态)

我的问题是:如何调用ModalBottomSheet的更新状态

showModalBottomSheet(
    context: context,
    builder: (context) {
      return Container(
        height: heightOfModalBottomSheet,
        child: RaisedButton(

            onPressed: () {
              setState(() {
                heightOfModalBottomSheet += 10;
              });

            }),
      );
    });

请参考以下工作代码。我为
showModalBottomSheet
创建了一个新的有状态小部件(
ModalBottomSheet
)。按下按钮后,我们正在重建
ModalBottomSheet
,现在更干净了。如果需要动画来更改高度,我们可以使用
AnimationController

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

class ModalBottomSheet extends StatefulWidget {
  _ModalBottomSheetState createState() => _ModalBottomSheetState();
}

class _ModalBottomSheetState extends State<ModalBottomSheet>
    with SingleTickerProviderStateMixin {
  var heightOfModalBottomSheet = 100.0;

  Widget build(BuildContext context) {
    return Container(
      height: heightOfModalBottomSheet,
      child: RaisedButton(
          child: Text("Press"),
          onPressed: () {
            heightOfModalBottomSheet += 100;
            setState(() {});
          }),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _MyHomePageState();
  }
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    Future(() => showModalBottomSheet(
        context: context,
        builder: (context) {
          return ModalBottomSheet();
        }));
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Modal example"),
      ),
    );
  }
}

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(title: 'Flutter Demo', home: new MyHomePage());
  }
}
导入'dart:async';
进口“包装:颤振/材料.省道”;
类ModalBottomSheet扩展StatefulWidget{
_ModalBottomSheetState createState()=>ModalBottomSheetState();
}
类_ModalBottomSheetState扩展状态
使用SingleTickerProviderStateMixin{
模型底板的var高度=100.0;
小部件构建(构建上下文){
返回容器(
高度:模块底板的高度,
孩子:升起按钮(
子:文本(“按”),
已按下:(){
模块底板的高度+=100;
setState((){});
}),
);
}
}
类MyHomePage扩展StatefulWidget{
@凌驾
状态createState(){
返回新的_MyHomePageState();
}
}
类_MyHomePageState扩展状态{
@凌驾
小部件构建(构建上下文){
未来(()=>showModalBottomSheet(
上下文:上下文,
生成器:(上下文){
返回ModalBottomSheet();
}));
归还新脚手架(
appBar:新的appBar(
标题:新文本(“模态示例”),
),
);
}
}
void main(){
runApp(新的MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回新的MaterialApp(标题:“颤振演示”,主页:new MyHomePage());
}
}

您可以使用
脚手架状态
中的
展示底图
。阅读更多关于此展示的信息

这将显示底部工作表并返回控制器
PersistentBottomSheetController
。使用此控制器,您可以调用
controller.SetState((){})
,它将重新呈现底部表单

这里有一个例子

PersistentBottomSheetController _controller; // <------ Instance variable
final _scaffoldKey = GlobalKey<ScaffoldState>(); // <---- Another instance variable
.
.
.
void _incrementBottomSheet(){
    _controller.setState(
        (){
            heightOfModalBottomSheet += 10;
        }
    )
}
.
void _createBottomSheet() async{
  _controller = await _scaffoldKey.currentState.showBottomSheet(
        context: context,
        builder: (context) {
           return Container(
               height: heightOfModalBottomSheet,
               child: RaisedButton(
               onPressed: () {
                  _incrementBottomSheet()
              }),
         );
      });
}

PersistentBottomSheetController\u controller;// 您可以使用Flatter的
StatefulBuilder
按如下方式包装您的ModalBottomSheet:

showModalBottomSheet(
    context: context,
    builder: (context) {
      return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState /*You can rename this!*/) {
        return Container(
          height: heightOfModalBottomSheet,
          child: RaisedButton(onPressed: () {
            setState(() {
              heightOfModalBottomSheet += 10;
            });
          }),
        );
      });
});
请注意,新的
setState
将覆盖您的主窗口小部件
setState
,但请确保您可以重命名它,以便您能够设置父窗口小部件和模式窗口小部件的状态

//This sets modal state
setModalState(() {
    heightOfModalBottomSheet += 10;
});
//This sets parent widget state
setState(() {
     heightOfModalBottomSheet += 10;
});

屏幕截图:


创建一个类:

类MyBottomSheet扩展StatefulWidget{
@凌驾
_MyBottomSheetState createState()=>\u MyBottomSheetState();
}
类MyBottomSheetState扩展了状态{
bool_标志=假;
@凌驾
小部件构建(构建上下文){
返回列(
儿童:[
飘动标志(
尺寸:300,
样式:flatterlogostyle.stacked,
text颜色:_标志?颜色。黑色:颜色。红色,
),
升起的按钮(
按下:()=>setState(()=>U标志=!\U标志),
子项:文本(“更改颜色”),
)
],
);
}
}
用法:

showModalBottomSheet(
上下文:上下文,
生成器:()=>MyBottomSheet(),
);

为showModalBottomSheet()创建一个单独的StatefulWidget,如

底部表单Statefulwidget

class MapBottomSheet extends StatefulWidget {
  @override
  _MapBottomSheetState createState() => _MapBottomSheetState();
}

class _MapBottomSheetState extends State<MapBottomSheet> {
  List<String> places = [];

  void _setPlaces(String place) {
    setState(() {
      places.add(place);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black12,
      child: Column(
        children: [
          AppTextField(
            hint: "Search",
            onEditingComplete: () {},
            onChanged: (String text) {},
            onSubmitted: (String text) async {
              // Await the http get response, then decode the json-formatted response.
              var response = await http.get(Uri.parse(
                  'https://api.mapbox.com/geocoding/v5/mapbox.places/$text.json?access_token=pk.eyJ1IjoidjNyc2lvbjkiLCJhIjoiY2ttNnZldmk1MHM2ODJxanh1ZHZqa2I3ZCJ9.e8pZsg87rHx9FSM0pDDtlA&country=PK&fuzzyMatch=false&place=park'));
              if (response.statusCode == 200) {
                Map<String, dynamic> data = jsonDecode(response.body);
                print(data.toString());

                List<dynamic> features = data['features'];

                features.forEach((dynamic feature) {
                  setState(() {
                    _setPlaces(feature['place_name']);
                  });
                });
              } else {
                print('Request failed with status: ${response.statusCode}.');
              }
            },
          ),
          Expanded(
            child: Container(
              height: 250.0,
              width: double.infinity,
              child: ListView.builder(
                  itemCount: places.length,
                  itemBuilder: (ctx, idx) {
                    return Container(
                      child: Text(places[idx]),
                    );
                  }),
            ),
          ),
        ],
      ),
    );
    
  }
}
类MapBottomSheet扩展StatefulWidget{
@凌驾
_MapBottomSheetState createState()=>MapBottomSheetState();
}
类(MapBottomSheetState扩展状态){
排名=[];
无效设置位置(字符串位置){
设置状态(){
地点。添加(地点);
});
}
@凌驾
小部件构建(构建上下文){
返回容器(
颜色:颜色。黑色,
子:列(
儿童:[
AppTextField(
提示:“搜索”,
onEditingComplete:(){},
onChanged:(字符串文本){},
OnSubmited:(字符串文本)异步{
//等待http get响应,然后解码json格式的响应。
var response=wait http.get(Uri.parse(
'https://api.mapbox.com/geocoding/v5/mapbox.places/$text.json?access_token=pk.eyj1ijoidjnyc2lvjkilchijoi2ttnzldmk1m2odjxanh1zhzqa2i3zcj9.e8pZsg87rHx9FSM0pDDtlA&country=pk&fuzzyMatch=false&place=park');
如果(response.statusCode==200){
Map data=jsonDecode(response.body);
打印(data.toString());
列表特征=数据['features'];
features.forEach((动态特性){
设置状态(){
_设置位置(特征['place_name']);
});
});
}否则{
打印('请求失败,状态:${response.statusCode}');
}
},
),
扩大(
子:容器(
高度:250.0,
宽度:double.infinity,
子项:ListView.builder(
itemCount:places.length,
项目生成器:(ctx、idx){
返回容器(
子项:文本(位置[idx]),
);
}),
),
),
],
),
);
}
}

您是否收到任何错误?因为它为meUse ChangeNotifier提供程序工作。这不是设置当前模式的状态,而是在旧模式的基础上创建一个新模式。每次按下按钮都会造成难看的效果。我同意。。。这就是我关闭p的原因
class MapBottomSheet extends StatefulWidget {
  @override
  _MapBottomSheetState createState() => _MapBottomSheetState();
}

class _MapBottomSheetState extends State<MapBottomSheet> {
  List<String> places = [];

  void _setPlaces(String place) {
    setState(() {
      places.add(place);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black12,
      child: Column(
        children: [
          AppTextField(
            hint: "Search",
            onEditingComplete: () {},
            onChanged: (String text) {},
            onSubmitted: (String text) async {
              // Await the http get response, then decode the json-formatted response.
              var response = await http.get(Uri.parse(
                  'https://api.mapbox.com/geocoding/v5/mapbox.places/$text.json?access_token=pk.eyJ1IjoidjNyc2lvbjkiLCJhIjoiY2ttNnZldmk1MHM2ODJxanh1ZHZqa2I3ZCJ9.e8pZsg87rHx9FSM0pDDtlA&country=PK&fuzzyMatch=false&place=park'));
              if (response.statusCode == 200) {
                Map<String, dynamic> data = jsonDecode(response.body);
                print(data.toString());

                List<dynamic> features = data['features'];

                features.forEach((dynamic feature) {
                  setState(() {
                    _setPlaces(feature['place_name']);
                  });
                });
              } else {
                print('Request failed with status: ${response.statusCode}.');
              }
            },
          ),
          Expanded(
            child: Container(
              height: 250.0,
              width: double.infinity,
              child: ListView.builder(
                  itemCount: places.length,
                  itemBuilder: (ctx, idx) {
                    return Container(
                      child: Text(places[idx]),
                    );
                  }),
            ),
          ),
        ],
      ),
    );
    
  }
}