Two ChangeNotifierProvider on two different pages - flutter

How can I provide two ChangeNotifierProvider for different pages.
The first page works fine but when I click button and switch to the other side the Provider is not working properly and show me this error:
Error: Could not find the correct Provider above this SecondPage Widget. My code:
Main:
void main() => runApp(App());
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => UserListViewModel(),
),
ChangeNotifierProvider(
create: (context) => AnimalViewModel(),
)
],
child: UserListPage(),
)
);
}
}
UserListPage:
class UserListPage extends StatefulWidget {
#override
_UserListPageState createState() => _UserListPageState();
}
class _UserListPageState extends State<UserListPage> {
#override
void initState() {
super.initState();
Provider.of<UserListViewModel>(context, listen: false).fetchUsers("");
}
#override
Widget build(BuildContext context) {
final vm = Provider.of<UserListViewModel>(context);
return Scaffold(
appBar: AppBar(
title: Text("Movies")
),
body: Container(
padding: EdgeInsets.all(10),
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Column(children: <Widget>[
Container(
padding: EdgeInsets.only(left: 10),
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(10)
),
child: RaisedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
},
textColor: Colors.white,
padding: const EdgeInsets.all(0.0),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFF0D47A1),
Color(0xFF1976D2),
Color(0xFF42A5F5),
],
),
),
padding: const EdgeInsets.all(10.0),
child:
const Text('Gradient Button', style: TextStyle(fontSize: 20)),
),
),
),
Expanded(
child: UserList(users: vm.users))
])
)
);
}
}
SecondPage:
class _SecondPageState extends State<SecondPage> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
final vm = Provider.of<AnimalViewModel>(context);
return Scaffold(
appBar: AppBar(
title: Text("Animals")
),
body: Container(
padding: EdgeInsets.all(10),
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Column(children: <Widget>[
Container(
padding: EdgeInsets.only(left: 10),
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(10)
),
child: RaisedButton(
onPressed: () {
vm.setName = 'BumBum';
},
textColor: Colors.white,
padding: const EdgeInsets.all(0.0),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFF0D47A1),
Color(0xFF1976D2),
Color(0xFF42A5F5),
],
),
),
padding: const EdgeInsets.all(10.0),
child:
const Text('Gradient Button', style: TextStyle(fontSize: 20)),
),
),
),
Expanded(
child: Text(vm.getName))
])
)
);
}
}

You need to move your MultiProvider above MaterialApp. Like this:
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => UserListViewModel(),
),
ChangeNotifierProvider(
create: (context) => AnimalViewModel(),
)
],
child: MaterialApp(
home: UserListPage(),
),
),
The reason you're getting the error is the home widget is a route and that's what MultiProvider wraps. So when you navigate from that route to SecondPage, that route is gone and it can not access MultiProvider

Related

Flutter: Navigator operation requested with a context that does not include a Navigator

when I click ElevatedButton(), Navigator.push() occurs Error: Navigator operation requested with a context that does not include a Navigator. But I make that ElevatedButton() in other dart file as widget, and I import It. It works well. What's the difference betweent make navigator button inside in code and import navigator button.
class GuideMainScreen extends StatelessWidget {
GuideMainScreen({super.key});
final _controller = PageController();
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: const Color(0xFFF4EDDB),
appBar: const AppbarSkip(),
body: Column(
children: [
SizedBox(
height: 570,
child: PageView(
controller: _controller,
children: const [
GuideHowScreen(),
GuideFocusScreen(),
GuideBreakScreen(),
],
),
),
Row(
children: [
const Padding(padding: EdgeInsets.only(left: 40)),
SmoothPageIndicator(
controller: _controller,
count: 3,
effect: const ExpandingDotsEffect(
activeDotColor: Color(0xFFE7626C),
dotColor: Color(
0xFF232B55,
),
),
),
const SizedBox()
],
),
const Padding(
padding: EdgeInsets.symmetric(
vertical: 45,
),
),
const SizedBox(
width: 181,
height: 49,
// Error
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HomeScreen(),
),
);
},
child: const Text(
'SKIP',
style: TextStyle(color: Colors.white),
),
);
// Works Well
child: SkipButton(),
),
],
),
),
);
}
}
this is SkiptButton() Widget which I write code in other dart file
import 'package:flutter/material.dart';
class SkipButton extends StatelessWidget {
const SkipButton({super.key});
#override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HomeScreen(),
),
);
},
child: const Text(
'SKIP',
style: TextStyle(color: Colors.white),
),
);
}
}

Hero animation is not working when navigating to new page flutter

I have product items in grid view which is a future builder, and wrapped with Hero Widget and gave a unique tag by id, and in detail new page also I wrapped with Hero Widget and gave same unique tag but the animation is working only when coming back to screen. I didn't understand why Hero animation is not working when navigating to a new page, maybe because of Future builder? or I made any mistake? don't know what happening, Can anyone Help me to achieve nice Hero animation. Below I provided my code. Please feel free to ask any questions. Thanks in advance.
main.dart
import 'package:flutter/material.dart';
import 'package:httprequest/screens/all_products.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const AllProductsScreen(),
);
}
}
all_products.dart
import 'package:flutter/material.dart';
import 'package:httprequest/screens/single_product.dart';
import 'package:httprequest/services/api_services.dart';
class AllProductsScreen extends StatefulWidget {
const AllProductsScreen({Key? key}) : super(key: key);
#override
_AllProductsScreenState createState() => _AllProductsScreenState();
}
class _AllProductsScreenState extends State<AllProductsScreen> {
Future ? products;
#override
void initState() {
// TODO: implement initState
products = ApiServices().getAllProducts();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Products"),
),
body: Container(
padding: EdgeInsets.all(8.0),
child: FutureBuilder(
future: products,
builder: (context, AsyncSnapshot snapshot){
if(snapshot.hasData){
return Center(
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 2 / 3,
crossAxisSpacing: 20,
mainAxisSpacing: 20),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext ctx, index) {
return GestureDetector(
child: Hero(
tag: snapshot.data[index]["id"],
child: Card(
child: Container(
padding: EdgeInsets.all(5.0),
child: Column(
children: [
Image.network(snapshot.data[index]["image"],height: 180,width: 180,),
Text(snapshot.data[index]["title"],textAlign: TextAlign.center,maxLines: 2,overflow: TextOverflow.ellipsis,),
Text("\$: ${snapshot.data[index]["price"]}")
],
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15)),
),
),
),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => SingleProduct(snapshot.data[index]["id"])));
},
);
}),
);
}
return const Center(child: CircularProgressIndicator(),);
},
),
),
);
}
}
single_product.dart
import 'package:flutter/material.dart';
import 'package:httprequest/services/api_services.dart';
class SingleProduct extends StatefulWidget {
final id;
SingleProduct(this.id);
#override
_SingleProductState createState() => _SingleProductState();
}
class _SingleProductState extends State<SingleProduct> {
Future ? product;
#override
void initState() {
// TODO: implement initState
product = ApiServices().getSingleProduct(widget.id);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Products"),
),
body: FutureBuilder(
future: product,
builder: (context,AsyncSnapshot snapshot){
if(snapshot.hasData){
return Container(
color: Colors.white,
child: Column(
children: [
Hero(
tag: widget.id,
child: Container(
color: Colors.transparent,
child: Center(
child: Image.network(snapshot.data["image"],height: 200,width: 200,),
),
),
),
Expanded(
child: Container(
color: Colors.transparent,
child: Card(
color: Colors.white,
elevation: 20.0,
shape: RoundedRectangleBorder(
//side: BorderSide(width: 0.2),
borderRadius: BorderRadius.only(topRight: Radius.circular(20),topLeft: Radius.circular(20))),
child: Container(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(snapshot.data["title"],textAlign: TextAlign.center,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16),),
SizedBox(height: 5,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("\$: ${snapshot.data["price"]}",style: TextStyle(fontSize: 16),),
Row(
children: [
Text(snapshot.data["rating"]["rate"].toString(),style: TextStyle(fontSize: 16),),
Icon(Icons.star,color: Colors.yellow,size: 20,),
],
),
],
),
SizedBox(height: 5,),
Text(("Category: ${snapshot.data["category"]}"),textAlign: TextAlign.left,style: TextStyle(fontSize: 16),),
SizedBox(height: 5,),
Text(snapshot.data["description"],textAlign: TextAlign.justify,style: TextStyle(fontSize: 16),),
],
),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
padding: EdgeInsets.all(15),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(50),
color: Colors.black,
),
height: 50,
width: 130,
//color: Colors.black,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.shopping_cart,color: Colors.white,),
Text("Add to cart",style: TextStyle(color: Colors.white),),
],
),
),
),
],
),
),
),
),
),
],
),
);
}
return Center(child: CircularProgressIndicator());
},
),
);
}
}
api_services.dart
import 'dart:developer';
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiServices {
Future getAllProducts() async {
var allProcuctsUri = Uri.parse('https://fakestoreapi.com/products');
var response = await http.get(allProcuctsUri);
log("All Products response : ${response.statusCode.toString()}");
log("All Products body : ${response.body}");
return json.decode(response.body);
}
Future getSingleProduct(int id) async {
var singleProcuctUri = Uri.parse('https://fakestoreapi.com/products/${id}');
var response = await http.get(singleProcuctUri);
log("Single Product response : ${response.statusCode.toString()}");
log("Single Product body : ${response.body}");
return json.decode(response.body);
}
}
you have to provide the same tag in hero widget to both the screens which you want to animate. you have wrap the widget which to animate with HeroAnimation and provide tag and then wrap the other screen with HeroAnimation and provide the same tag to both the HeroAnimation widgets..
to check whether two tags are same first print snapshot.data[index]["id"] of all_products.dart and widget.id of single_product.dart.
if the second page tag is getting null, please initialize a variable inside build of single_product.dart like
#override
String finalid=widget.id; //add this and get reference from this
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Products"),
),
it would be better if both tags are in String format.

Issue with provider when navigating between screens

I'm trying to learn more about provider but I'm facing an issue with an app I'm developing, specifically when I navigate to a screen. When I press on the button to take me to the history_screen is when I get an error from Provider, all the providers are declared at the top of the tree so not really sure why there's still an error.
Hopefully someone can help me!
See my code below and the error I get:
Main.dart
void main() {
runApp(
MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
StreamProvider<List<Meds>>.value(
value: MedicinesNotifier().medicinesStream(),
initialData: MedicinesNotifier().meds,
updateShouldNotify: (_, __) => true),
//ChangeNotifierProvider<MedicinesNotifier>(create: (_) => MedicinesNotifier()),
ProxyProvider<List<Meds>,MedicinesNotifier>(
update:
(BuildContext context, List<Meds> meds1, MedicinesNotifier? medNoti) => MedicinesNotifier.med(meds1)
),
ChangeNotifierProvider<SearchHistoryData>(create: (_) => SearchHistoryData()),
],
child: MaterialApp(
title: 'Flutter Demo',
/*theme: ThemeData(
primarySwatch: Colors.blueGrey,
),*/
home: MyHomePage(),
),
);
}
}
home_page.dart
class _MyHomePageState extends State<MyHomePage> {
List<Meds> medFiltered = [];
TextEditingController searchController = new TextEditingController();
String searchText = "";
#override
Widget build(BuildContext context) {
bool isSearching = searchController.text.isNotEmpty;
return Scaffold(
bottomNavigationBar: BottomBar(),
body: SafeArea(
child: Container(
padding: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Container(
child: TextField(
controller: searchController,
decoration: InputDecoration(
labelText: "Search",
border: new OutlineInputBorder(
borderSide: new BorderSide(
color: Theme.of(context).primaryColor,
),
borderRadius: BorderRadius.circular(30.0),
),
prefixIcon: Icon(Icons.search),
),
onChanged: (value) {
Provider.of<MedicinesNotifier>(context, listen: false)
.changeSearchString(value);
},
),
),
Expanded(
child:
ListView.builder(
shrinkWrap: true,
itemCount: isSearching == true
? context
.watch<MedicinesNotifier>()
.meds
.length
: context
.watch<List<Meds>>()
.length,
itemBuilder: (context, index) {
Meds med = isSearching == true
? context
.watch<MedicinesNotifier>()
.meds
[index]
: context
.watch<List<Meds>>()[index]; //medsStreamed[index];
return ListTile(
onTap: () {
context.read<MedicinesNotifier>().addHistory(med);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatScreen(
med: context.watch<MedicinesNotifier>().findMedicine(med),
)));
},
title: Text(med.name),
subtitle: Text(med.description.substring(0, 10)),
);
},
),
),
],
),
),
),
);
}
}
BottomBar widget
class BottomBar extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BottomAppBar(
shape: CircularNotchedRectangle(),
color: Theme.of(context).primaryColor,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
icon: Icon(Icons.search),
color: Colors.white,
iconSize: 40.0,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => MyHomePage()));
},
),
IconButton(
color: Colors.white,
icon: Icon(Icons.history_edu),
iconSize: 40.0,
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => HistoryScreen()));
},**//Causing the issue**
),
]),
);
}
}
history_screen.dart
class HistoryScreen extends StatefulWidget {
const HistoryScreen({Key? key}) : super(key: key);
#override
_HistoryScreenState createState() => _HistoryScreenState();
}
class _HistoryScreenState extends State<HistoryScreen> {
#override
Widget build(BuildContext context) {
//List<Meds> temp1 = context.watch<MedicinesNotifier>().history;
return Scaffold(
bottomNavigationBar: BottomBar(),
body: SafeArea(
child: Column(
children: <Widget>[
Container(
color: Theme.of(context).primaryColor,
child: Padding(
padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 30.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
onPressed: () {},
child: Text(
"Filter",
style: TextStyle(
color: Colors.white,
),
),
),
],
),
],
),
),
),
Expanded(
child: Container(
//color: Colors.white54,
decoration: BoxDecoration(
color: Colors.white30,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.0),
topRight: Radius.circular(30.0),
),
),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.0),
topRight: Radius.circular(30.0),
),
child: Consumer<SearchHistoryData?>(**//Using Consumer here**
builder: (context, searchHistoryData, child) {
//assert(child != null);
return ListView.builder(
itemCount: searchHistoryData!.sizeOfHistory(),
itemBuilder: (BuildContext context, int index) {
//final historyData =
return Container(
margin: EdgeInsets.only(...
Exception caught
The following ProviderNotFoundException was thrown building Consumer<SearchHistoryData?>(dirty):
Error: Could not find the correct Provider<SearchHistoryData?> above this Consumer<SearchHistoryData?> Widget
This happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:
You added a new provider in your main.dart and performed a hot-reload.
To fix, perform a hot-restart.
The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
You used a BuildContext that is an ancestor of the provider you are trying to read.
Make sure that Consumer<SearchHistoryData?> is under your MultiProvider/Provider<SearchHistoryData?>.
This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
consider using builder like so:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}

mediaquery.of() called with a context that does not contain a media query.No media query could be found starting from the context

Hi I could not resolve this error Exception has occurred. FlutterError (MediaQuery.of() called with a context that does not contain a MediaQuery. No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of(). This can happen because you do not have a Widgets App or Material App widget (those widgets introduce a MediaQuery), or it can happen if the context you use comes from a widget above those widgets. The context used was: Scaffold)
Here is the code:
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(HomePage());
}
class HomePage extends StatelessWidget {
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
gotoSecondActivity(BuildContext context){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondActivity()),
);
}
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<AuthenticationService>(
create: (_) => AuthenticationService(FirebaseAuth.instance),
),
StreamProvider(
create: (context) => context.read<AuthenticationService>().authStateChanges,
)
],
child:Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: RaisedButton(
onPressed: () {
context.read<AuthenticationService>().signIn(
email: emailController.text.trim(),
password: passwordController.text.trim(),
);
gotoSecondActivity(context);
},
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/loginHeader.png'),
fit: BoxFit.fill
)
),
child: Stack(
children: <Widget>[
],
),
),
Padding(
padding: EdgeInsets.all(30.0),
child: Column(
children: <Widget>[
FadeAnimation(1.8, Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Color.fromRGBO(143, 148, 251, .2),
blurRadius: 20.0,
offset: Offset(0, 10)
)
]
),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(
color: Colors.grey[100]))
),
child: TextField(
controller:emailController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Email or Phone number",
hintStyle: TextStyle(
color: Colors.grey[400])
),
),
),
Container(
padding: EdgeInsets.all(8.0),
child: TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Password",
hintStyle: TextStyle(
color: Colors.grey[400])
),
),
)
],
),
)),
SizedBox(height: 30,),
FadeAnimation(2, Container(
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
gradient: LinearGradient(
colors: [
Color.fromRGBO(214, 0, 27, 1),
Color.fromRGBO(214, 0, 27, 1),
]
)
),
child: Center(
child: Text("Login", style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),),
),
)),
SizedBox(height: 70,),
FadeAnimation(1.5, Text("Forgot Password?",
style: TextStyle(
color: Color.fromRGBO(214, 0, 27, 1)),)),
],
),
)
],
),
),
),
),
),
);
}
}
You can resolve the issue by using the below steps,
Yes the MediaQuery.of(context)--> is from on the MaterialApp and WidgetApp only
Step 1:
void main(){
runApp(MyApp());
}
Step 2:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MediaQuery',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
Step 3:
class HomePage extends StatelessWidget {
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
gotoSecondActivity(BuildContext context){
var size = MediaQuery.of(context).size;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: RaisedButton(
onPressed: () {
gotoSecondActivity(context);
},
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
child: Stack(
children: <Widget>[
],
),
),
Padding(
padding: EdgeInsets.all(30.0),
child: Column(
children: <Widget>[
Container(child: Text('hello'),)
],
),
)
],
),
),
),
),
);
}
}
In Your Code :
#override
Widget build(BuildContext context) {
Var mediaQuery = MediaQuery.of(context).size;
return MultiProvider(
Just Correct this .it will work

How to fix 'Navigator operation requested with a context that does not include a Navigator. ' in flutter

I encounter this error.
Navigator operation requested with a context that does not include a Navigator.
I follow the guidelines on the Internet but i'm still confused on how to fix this error. Here is my code
class SecondScreen extends StatelessWidget{
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Colors.amberAccent, Colors.red]),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,// add Column
children: <Widget>[
Text('Welcome', style: TextStyle( // your text
fontSize: 50.0,
fontWeight: FontWeight.bold,
color: Colors.white)
),
RaisedButton(onPressed: () {
Navigator.pop(context);
},
child: Text('Button'),
shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)
),
color: Colors.white,
splashColor: Colors.blue,
textColor: Color(0xfffe67e22),
), // your button beneath text
],
),
),
),
);
}
}
```
The problem is not in your second page. Actually the problem is in your main.dart; You should create a new widget for home property of MaterialApp instead of using a Scaffold widget directly;
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: App(),
),
);
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => SecondPage()),
),
child: Text("SecondPage"),
),
],
),
),
);
}
}
Screenshot:
Full code:
void main() => runApp(MaterialApp(home: MyApp(), debugShowCheckedModeBanner: false));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [Colors.amberAccent, Colors.red]),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center, // add Column
children: <Widget>[
Text('Welcome',
style: TextStyle(
// your text
fontSize: 50.0,
fontWeight: FontWeight.bold,
color: Colors.white)),
RaisedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return SecondScreen();
}));
},
child: Text('Button'),
shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)),
color: Colors.white,
splashColor: Colors.blue,
textColor: Color(0xfffe67e22),
), // your button beneath text
],
),
),
),
);
}
}
class SecondScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [Colors.amberAccent, Colors.red]),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center, // add Column
children: <Widget>[
Text('Welcome',
style: TextStyle(
// your text
fontSize: 50.0,
fontWeight: FontWeight.bold,
color: Colors.white)),
RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Button'),
shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)),
color: Colors.white,
splashColor: Colors.blue,
textColor: Color(0xfffe67e22),
), // your button beneath text
],
),
),
),
);
}
}