gpt4 book ai didi

dart - OpenFlutter/flutter_oktoast 只显示在主页上?

转载 作者:IT王子 更新时间:2023-10-29 07:20:49 27 4
gpt4 key购买 nike

我正在使用 this在我的应用程序中显示自定义 toast 的库。我的应用程序中有多个页面。问题是,即使我从任何其他页面调用 showToastWidget(...),toast 也会出现在主页上。

主页

  @override
Widget build(BuildContext context) {
return OKToast(
child: Scaffold(
backgroundColor: Theme.of(context).accentColor,
body: Center(
child: SizedBox(
height: 50,
width: 50,
child: Image(image: AssetImage('assets/ic_logo.png')),
),
),
),
);
}

第 2 页

@override
Widget build(BuildContext context) {
return OKToast(
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Reset Password'),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(20),
child: FlatButton(
onPressed: () {
showToastWidget(
Text('Hello. I am Toast!!!'),
duration: Duration(seconds: 2),
);
},
child: Text('Show'),
),
),
),
),
);
}

当我从此页面调用 showToastWidget(...) 时,它出现在主页上

编辑 1当我将上下文传递给 showToastWidget()

时出现此异常
I/flutter (24327): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter (24327): The getter 'position' was called on null.
I/flutter (24327): Receiver: null
I/flutter (24327): Tried calling: position
I/flutter (24327):
I/flutter (24327): When the exception was thrown, this was the stack:
I/flutter (24327): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter (24327): #1 showToastWidget (package:oktoast/src/toast.dart:210:40)

最佳答案

看起来 OKToast 库不支持同一应用中的多个 OKToast 小部件。您必须将整个应用程序包装在 OKToast 小部件中,完整示例:

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

void main() => runApp(App());

class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return OKToast(
child: MaterialApp(
home: MainPage(),
),
);
}
}

class MainPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).accentColor,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FlatButton(
child: Text("Show"),
onPressed: () {
showToast(
"Main Page toast",
duration: Duration(seconds: 2),
);
},
),
SizedBox(height: 12.0),
FlatButton(
child: Text("Go to next page"),
onPressed: () => _goToNextPage(context),
),
],
),
),
);
}

void _goToNextPage(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage(),
),
);
}
}

class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Second Page"),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(20),
child: FlatButton(
onPressed: () {
showToast(
"Second Page toast",
duration: Duration(seconds: 2),
);
},
child: Text('Show'),
),
),
),
);
}
}

关于dart - OpenFlutter/flutter_oktoast 只显示在主页上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55726339/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com