警报对话框颤动错误仅有效值 0:1

时间:2021-02-13 06:23:38

标签: flutter

我做了一个简单的提醒功能

Github:https://github.com/mohammad092/first

void newAlert(BuildContext context) {
  showDialog(
    context: context,
    builder: (BuildContext context){
      return AlertDialog(
        title: Text('title text'),
        content: Text('content text'),
        actions: [
          FlatButton(
            onPressed: (){
              Navigator.of(context).pop();
            },
            child: Text('dismiss'),
          ),
        ],
      );
    },
  );
}

然后我将它导入到我的 main.dart 我也导入了具有警报功能的文件

body: RaisedButton(
        child: Text('Alert'),
        onPressed: () {
          newAlert(context);
        }),
...

当我按下设备上的按钮时,它一直说:

======== Exception caught by gesture library ================
The following RangeError was thrown while routing a pointer event:
RangeError (index): Invalid value: Only valid value is 0: 1

2 个答案:

答案 0 :(得分:1)

您收到错误是因为您的 main.dart 没有正确实现。您直接在 RaisedButton 类中声明您的 MyApp,而您应该制作另一个小部件并将其传递给MyApp,这将给出正确的 context 以显示警报。

将您的 main.dart 更改为:

import 'package:flutter/material.dart';
import 'package:your_project/alert.dart';

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(
      body: Center(
        child: RaisedButton(
          child: Text('Alert'),
          onPressed: () {
            newAlert(context);
          },
        ),
      ),
    );
  }
}

答案 1 :(得分:0)

使用下面的代码

Future<void> _showMyDialog() async {
  return showDialog<void>(
    context: context,
    barrierDismissible: false, // user must tap button!
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('AlertDialog Title'),
        content: SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text('This is a demo alert dialog.'),
              Text('Would you like to approve of this message?'),
            ],
          ),
        ),
        actions: <Widget>[
          TextButton(
            child: Text('Approve'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

body: RaisedButton(
        child: Text('Alert'),
        onPressed: () {
          _showMyDialog()
        }),
...