【问题标题】:I want to add a SnackBar inside my flutter application我想在我的颤振应用程序中添加一个 SnackBar
【发布时间】:2021-03-26 01:29:53
【问题描述】:

我想添加一个小吃栏,告诉用户在添加到正文的图像超过 2 时向上滚动。问题是我不能将小吃栏放在脚手架中,因为添加图像按钮只是脚手架小部件中的引用。我刚开始提问,所以我可能没有正确提问。

class App extends StatefulWidget {
  createState() {
    return AppState();
  }
}

class AppState extends State<App> {
  int counter = 0;
  List<ImageModel> images = [];

  void fetchImage() async {
    counter++;
    while (counter > 2) {
      Scaffold.of(context).showSnackBar(SnackBar(
        content: Text('Scroll Up'),
        duration: Duration(seconds: 2),
      ));
    }
    var response =
        await get('http://jsonplaceholder.typicode.com/photos/$counter');

    var imageModel = ImageModel.fromJson(json.decode(response.body));
    setState(
      () {
        images.add(imageModel);
      },
    );
  }

  Widget build(context) {
    return MaterialApp(
      home: Scaffold(
        body: ImageList(images),
        backgroundColor: Colors.blueGrey.shade200,
        bottomNavigationBar: BottomAppBar(
          shape: const CircularNotchedRectangle(),
          child: Container(
            height: 50.0,
            //color: Colors.blue,
          ),
        ),
        floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.blueGrey,
          child: Icon(Icons.add),
          onPressed: fetchImage,
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        appBar: AppBar(
          title: Text("Let's see images!"),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter flutter-layout snackbar


    【解决方案1】:

    显示 Snackbar 的最佳和最简单的方法是使用 GlobalKey。只需创建一个 GlobalKey ,将其分配给 Scaffold 并使用此键来显示 SnackBar。例如:

    class _WidgetState extends State<YourStatefulWidget> {
      final scaffoldKey=GlobalKey<ScaffoldState>();
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          key:scaffoldKey,
          body: Center(
            child: RaisedButton(
            child:Text("Press Me"),
            onPressed:(){
                scaffoldKey.currentState.showSnackBar(
                SnackBar(content:Text("YO"))
                );
              },
            ),
          ),
        );
      }
    }
    

    【讨论】:

    • 我能够找到使用全局键显示snackbar 的方式,但我认为我无法使用while 循环来调节snackbar。我的设备断开连接。
    【解决方案2】:

    您可以尝试在调用 fetchImage() 方法时发送上下文参数,如下所示:

       onPressed: () 
             {
               fetchImage(context);
             }
    

    然后:

       void fetchImage(BuildContext context) async {
       
    

    【讨论】:

    • fetchImage 函数返回一个 void,onPressed 函数不能使用它
    • 我通过更改 onPressed 方法改进了答案。
    猜你喜欢
    • 2019-12-14
    • 2020-08-20
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2019-04-29
    相关资源
    最近更新 更多