我有下面的代码,它在Ffltter中创建了一个屏幕上的年龄输入域.当用户try 转到下一个屏幕而不键入内容时,我想向用户显示祝wine 词.我可以打印出我希望在 cogo toast 中显示的内容,但由于某些原因,scaffold.showSnackBar函数不适合我.有人能帮我解决这个问题吗?以下是代码:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:workout_app/Screens/Components/Sign_Up_Screens/screen1.dart';
import 'package:workout_app/Screens/Components/Sign_Up_Screens/screen3.dart';

class screen2 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Main();
}

class Main extends State<screen2> {
  void returnScreen(context) {
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(
        fullscreenDialog: true,
        builder: (context) => screen1(),
      ),
    );
  }

    
  @override
  void initState() {
    loadData();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }
  

  @override
  int age = 10;
  bool nextValid = false;

  void toast(String text) {
    print(text);
    final scaffold = ScaffoldMessenger.of(context);
    scaffold.showSnackBar(
      SnackBar(
        content: Text(text),
      ),
    );
  }

  void submitData() async {
    if(nextValid == false) {
      toast('Please input your age');
      return;
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt('age', age);
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(
        fullscreenDialog: true,
        builder: (context) => SingleSelectListViewWithLogo(items : ['Tone Up - You want visible muscles with as little mass as possible and a low body fat percentage', 'Bulk Up - You want large, defined muscles, with a low percentage of body fat', 'Get Jacked - You want to lift an insane amount of weight and don\'t care about body fat or muscle definition']),
      ),
    );
  }

  void loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    try {
      int? x = prefs.getInt('age');
      print(x);
      if(x != null) {
        setState(() => {age = x});
      }
    } catch (Exception){
      //continue;
    }
  }

  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Material(
      child: Container (
        decoration: const BoxDecoration(color: Colors.grey),
        height: size.height,
        width: double.infinity,
        child: Stack(
          children: <Widget> [
            Positioned(
              top: size.height * .06,
              left: size.width * .03,
              child: InkWell(
                onTap: () {
                  returnScreen(context);
                },
                child: Image.asset(
                  alignment: Alignment.topLeft,
                  "assets/images/back2.png",
                  width: size.width * .07,
                ),
              ),
            ),
            Positioned(
              top: size.height * .09,
              left: size.width * .42,
              child: const Text(
                style: TextStyle(fontSize: 30, color: Color.fromARGB(255, 4, 3, 3)),
                'Next,'
              )
            ),
            Positioned(
              top: size.height * .15,
              left: size.width * .16,
              child: const Text(
                style: TextStyle(fontSize: 20, color: Color.fromARGB(255, 76, 74, 74)),
                'Lets customize your workout!'
              )
            ),
            Positioned (
              top: size.height * .23,
              left: size.width * .28,
              child: Image.asset(
                "assets/images/age.png",
                width: size.width * .4
              )
            ),
            Positioned(
              top: size.height * .55,
              left: size.width * .15,
              child: const Text(
                style: TextStyle(fontSize: 25, color: Color.fromARGB(255, 21, 17, 17)),
                'What\'s your current age?'
              )
            ),
            Positioned (
              top: size.height * .7,
              left: size.width * .1,
              child: SliderTheme(
                data: const SliderThemeData(
                  trackHeight: 30,
                  inactiveTrackColor: Color.fromARGB(255, 255, 255, 255),
                  activeTrackColor: Color.fromARGB(255, 50, 45, 45),
                  thumbColor: Colors.black,
                  disabledActiveTrackColor: Colors.black,
                  disabledInactiveTrackColor: Colors.black12,
                  thumbShape: RoundSliderThumbShape(enabledThumbRadius: 25.0),
                ),
                child: Container (
                  width: size.width * .8,
                  child: Slider(
                    label: "Select Age",
                    value: age.toDouble(),
                    onChanged: (value) {
                      setState(() {
                        age = value.toInt();
                        nextValid = true;
                      });
                    },
                    min: 10,
                    max: 99,
                  )
                )
              )
            ),
            Positioned (
              top: size.height * .62,
              left: size.width * .28,
              child: Text(
                age.toString(),
                style: const TextStyle(
                  fontSize: 40.0,
                ),
              ),
            ),
            Positioned (
              top: size.height * .64,
              left: size.width * .42,
              child: const Text (
                'years old',
                style: TextStyle(
                  fontSize: 25.0,
                ),
              )
            ),
            Positioned(
              top: size.height * .86,
              left: size.width * .1,
              child: SizedBox(
                width: size.width * .8,
                height: size.height * .08,
                child: ElevatedButton(
                  style: ButtonStyle(                  
                    backgroundColor: MaterialStateProperty.all<Color>(!nextValid ? Color.fromRGBO(69, 75, 85, 1) : Color.fromARGB(255, 0, 147, 246)),
                  ),
                  child: const Text('Continue',
                    style: TextStyle(fontSize: 20),
                  ),
                  onPressed: () async {
                    submitData();
                  },
                ),
              ),
            ),
          ]
        )
      )
    );
  }
}

推荐答案

让我们一起来研究这个问题,我想先给你看问题,然后再给你看解决方案.

问题: 您正在try 将SnackBar弹出到屏幕,而不是将Scaffold小部件作为父部件.打印到调试控制台上的问题:

ScaffoldMessenger.showSnackBar was called, but there are currently no descendant Scaffolds to present to.

这条消息告诉我们,当所有Scaffold的列表为空时,Snackbar不可能出现在屏幕上.

解决方法:用Scaffold将子元素们包起来,这样就可以显示SnackBar.

@override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Material(
      //Wrap the children with a Scaffold in order to use ScaffoldMessenger
      child: Scaffold(
        body: Container(
          decoration: const BoxDecoration(color: Colors.grey),
          height: size.height,
          width: double.infinity,
          child: Stack(
            children: <Widget>[
              Positioned(
                top: size.height * .06,
                left: size.width * .03,
                child: InkWell(
                  onTap: () {
                    returnScreen(context);
                  },
                  child: Image.asset(
                    alignment: Alignment.topLeft,
                    "assets/images/back2.png",
                    width: size.width * .07,
                  ),
                ),
              ),
              Positioned(
                  top: size.height * .09,
                  left: size.width * .42,
                  child: const Text(
                      style: TextStyle(
                          fontSize: 30, color: Color.fromARGB(255, 4, 3, 3)),
                      'Next,')),
              Positioned(
                  top: size.height * .15,
                  left: size.width * .16,
                  child: const Text(
                      style: TextStyle(
                          fontSize: 20, color: Color.fromARGB(255, 76, 74, 74)),
                      'Lets customize your workout!')),
              Positioned(
                  top: size.height * .23,
                  left: size.width * .28,
                  child: Image.asset("assets/images/age.png",
                      width: size.width * .4)),
              Positioned(
                  top: size.height * .55,
                  left: size.width * .15,
                  child: const Text(
                      style: TextStyle(
                          fontSize: 25, color: Color.fromARGB(255, 21, 17, 17)),
                      'What\'s your current age?')),
              Positioned(
                  top: size.height * .7,
                  left: size.width * .1,
                  child: SliderTheme(
                      data: const SliderThemeData(
                        trackHeight: 30,
                        inactiveTrackColor: Color.fromARGB(255, 255, 255, 255),
                        activeTrackColor: Color.fromARGB(255, 50, 45, 45),
                        thumbColor: Colors.black,
                        disabledActiveTrackColor: Colors.black,
                        disabledInactiveTrackColor: Colors.black12,
                        thumbShape:
                            RoundSliderThumbShape(enabledThumbRadius: 25.0),
                      ),
                      child: SizedBox(
                          width: size.width * .8,
                          child: Slider(
                            label: "Select Age",
                            value: age.toDouble(),
                            onChanged: (value) {
                              setState(() {
                                age = value.toInt();
                                nextValid = true;
                              });
                            },
                            min: 10,
                            max: 99,
                          )))),
              Positioned(
                top: size.height * .62,
                left: size.width * .28,
                child: Text(
                  age.toString(),
                  style: const TextStyle(
                    fontSize: 40.0,
                  ),
                ),
              ),
              Positioned(
                  top: size.height * .64,
                  left: size.width * .42,
                  child: const Text(
                    'years old',
                    style: TextStyle(
                      fontSize: 25.0,
                    ),
                  )),
              Positioned(
                top: size.height * .86,
                left: size.width * .1,
                child: SizedBox(
                  width: size.width * .8,
                  height: size.height * .08,
                  child: ElevatedButton(
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all<Color>(
                          !nextValid
                              ? const Color.fromRGBO(69, 75, 85, 1)
                              : const Color.fromARGB(255, 0, 147, 246)),
                    ),
                    child: const Text(
                      'Continue',
                      style: TextStyle(fontSize: 20),
                    ),
                    onPressed: () async {
                      submitData();
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

编辑:我强烈建议你go 看看Flutter cookbook个在那里展示快餐栏和其他有用的东西:).

Ios相关问答推荐

如何访问iOS模拟器中的zoom 设置?(在搜索中列出,但不可见)

SWIFT用户界面检测手势的开始和结束

iOS 17-在Xcode 15中添加导航控制器时,导航栏不会立即显示

为什么AVSpeechSynthesizer复制的信息比我的文本多?

iOS应用程序冻结在UICollectionView代码,但我没有';没有任何UICollectionViews

在 Swift 项目中使用情节提要加载 obj-c 文件

如何在Collection 后更改并保留按钮 colored颜色 ,然后在 SwiftUI 中切换回来?

SwiftUI 切换语句

clipShape swift的三元

Swift 图表:.chartYScale 似乎只适用于 100 的增量?

在使用 Github Actions 时,我面临权限被拒绝错误

将视图(例如 Text())不透明度设置为 0 或将背景设置为 Color.clear 会导致它不被绘制

如何在保持纵横比的同时zoom UIView 的内容以适应目标矩形?

如何在 iOS 的 xib 中设置十六进制 colored颜色 代码

Xcode 11 向后兼容性:UIWindowScene 仅在 iOS 13 或更高版本中可用

Xcode 8:函数类型不能有参数标签 destruct 我的构建

如何在键盘上方添加工具栏?

无效的 iPhone 应用程序二进制文件

我可以在 UIScrollView 中使用 UIRefreshControl 吗?

你如何以编程方式从视图控制器中画一条线?