I am new to flutter so here is my code where its printing one centre text but I need a button under the text.
import 'package:flutter/material.dart';
void main()
{
runApp(MaterialApp(
title: 'Hello Flutter',
home: HomeWidget(),
));
}
class HomeWidget extends StatelessWidget
{
#override
Widget build(BuildContext context)
{
return Material(
child: Container(child: Center(child: Text('Hello World Of Flutter Development'),),),
// Need Button Here beneath Text
);
} //Widget
} //End of Class
use - Column Widget.
Learn more about drawing Layouts:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: 'Hello Flutter',
home: HomeWidget(),
));
}
class HomeWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
Center(
child: Text('Hello World Of Flutter Development'),
),
RaisedButton(onPressed: (){},child: Text('Button'),) // Button under Text
]),
);
} //Widget
}
Use Column Widget
Column(
children: [
Text('Hello World Of Flutter Development'),
FlatButton(onPressed:() {}, child:Text('name on button')),
],
)
Related
I am trying out flutter, here I am having a simple card view, where there is an add AddButton , when the button is pressed new card is being added.
Now, i wanted to have it scrollable so added ListView and an expanded Widget in the Column. Here is the code...
import 'package:flutter/material.dart';
import './products.dart';
import './product_control.dart';
class ProductManger extends StatefulWidget {
final String startingProduct;
ProductManger({this.startingProduct = "Sweet Tester"});
#override
State<StatefulWidget> createState() {
return _ProductManagerState();
}
}
class _ProductManagerState extends State<ProductManger> {
List<String> _products = ['Food Tester'];
#override
void initState() {
_products.add(widget.startingProduct);
super.initState();
}
void _addProducts(String product) {
setState(() {
_products.add(product);
});
}
#override
Widget build(BuildContext context) {
return Column(children: [
Container(margin: EdgeInsets.all(10.0), child: ProductControl(_addProducts)),
Expanded(child: Products(_products))
]);
}
}
If I change that Expanded to Container with height, it works as expected, but now, nothing is being displayed except a button.
I am currently following a tutorial, exact same code is written, however, version of flutter is 0.3.2 and i am using 1.5
Or there could be some issue with the emulator?
Hope this helps.
Here is the listView code
import 'package:flutter/material.dart';
class Products extends StatelessWidget {
final List<String> products;
Products([this.products = const []]);
#override
Widget build(BuildContext context) {
return ListView(
children: products
.map((element) => Card(
child: Column(
children: <Widget>[
Image.asset('assets/food.jpg'),
Text(element)
],
),
))
.toList());
}
}
This is what is visible when i use Container with height 300.0 insted to expand
And when i use expand, this is what being shown
Please try to change
#override
Widget build(BuildContext context) {
return Column(children: [
Container(margin: EdgeInsets.all(10.0), child: ProductControl(_addProducts)),
Expanded(child: Products(_products))
]);
}
To
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column: children: [
Container(
margin: EdgeInsets.all(10.0),
child: ProductControl(_addProducts)),
Expanded(child: Products(_products))
]);
}
If it does not work , Please give a look to SingleChildeScrollView
Ok, so after hours of time I found out finally, the error was in my main.dart file.
Initially, the code was
import 'package:flutter/material.dart';
import './product_manager.dart';
import 'package:flutter/rendering.dart';
void main(){
debugPaintSizeEnabled=true;
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.deepOrange,
accentColor: Colors.deepPurple
),
home: Scaffold(
appBar: AppBar(
title: Text("Alpit anand"),
),
body: Column(
children: [ProductManger()],
)),
);
}
}
But when i changed to
import 'package:flutter/material.dart';
import './product_manager.dart';
import 'package:flutter/rendering.dart';
void main(){
debugPaintSizeEnabled=true;
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.deepOrange,
accentColor: Colors.deepPurple
),
home: Scaffold(
appBar: AppBar(
title: Text("Alpit anand"),
),
body:
ProductManger(),
),
);
}
}
Thanks to pskink, you really helped me out. Thanks for your time. Although I still have to find out, why it wasn't working that way.
Currently, I am trying to learn how bloc pattern works but i have some problems. I am trying to use BLOC pattern on flutter counter application which is default application for flutter project. Here is my main (layout) code:
import 'package:flutter/material.dart';
import 'package:suaybtest/my-home-page-state.dart';
import 'my-home-page-bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
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) {
final MyHomePageBloc _bloc = MyHomePageBloc();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: BlocBuilder<MyHomePageEvent, MyHomePageState>(
bloc: _bloc,
builder: (context, MyHomePageState state) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'${state.counter}',
style: Theme.of(context).textTheme.display1,
),
],
),
);
}),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
onPressed: () {
_bloc.dispatch(MyHomePageEvent.increment);
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
FloatingActionButton(
onPressed: () {
_bloc.dispatch(MyHomePageEvent.decrement);
},
tooltip: 'Decrement',
child: Icon(Icons.remove),
),
],
));
}
#override
void dispose() {
super.dispose();
}
}
Bloc page is this:
import 'package:bloc/bloc.dart';
import 'package:suaybtest/my-home-page-state.dart';
enum MyHomePageEvent {
increment,
decrement,
}
class MyHomePageBloc extends Bloc<MyHomePageEvent, MyHomePageState> {
#override
MyHomePageState get initialState => MyHomePageState.initial();
#override
Stream<MyHomePageState> mapEventToState(MyHomePageEvent event) async* {
MyHomePageState state = currentState;
switch (event) {
case MyHomePageEvent.increment:
state.counter++;
yield state;
break;
case MyHomePageEvent.decrement:
state.counter--;
yield state;
break;
}
}
}
and finally here is my state
class MyHomePageState {
int counter;
MyHomePageState._();
factory MyHomePageState.initial(){
return MyHomePageState._()..counter = 0;
}
}
I know there is no need to use state class like this because I have just one variable. However this is the closest sample for real world app.
The problem here when I click the buttons it works counter increasing you can display it in debug mode but build function of blocbuilder does not reload.
I use this library
dependencies:
flutter_bloc: ^0.11.1
I am new to Flutter and I wanted to have splash screen in my app. I used initState() and the navigator. But it didn't work. The app opens the splashscreen appears but after that it does not navigate to the next screen.
My main.dart
import 'package:flutter/material.dart';
import 'package:bmi/HomePage.dart';
import 'dart:async';
main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
#override
Widget build(BuildContext context) {
return SplashScreen();
}
}
class SplashScreen extends StatefulWidget{
#override
State<StatefulWidget> createState() {
return SplashScreenState();
}
}
class SplashScreenState extends State<SplashScreen>{
#override
void initState() {
super.initState();
Future.delayed(
Duration(
seconds: 4
),
(){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
)
);
}
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.red,
body: Text(
'Welcome to BMI Calculator',
style: new TextStyle(
fontSize: 15.0,
color: Colors.white,
fontWeight: FontWeight.bold
),
),
),
);
}
}
And my HomePage.dart
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget{
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'BMI Calculator',
style: new TextStyle(
color: Colors.white
),
),
),
),
);
}
}
How can I resolve this?
Since I am new to flutter I dont know whether this is the right way to implement splashScreen if there are any other easier ways can you please suggest that also.
Thank you in advance.
Code Corrected:
MaterialApp should be the parent(root) of all Widgets.
import 'package:flutter/material.dart';
import 'package:bmi/HomePage.dart';
import 'dart:async';
main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: SplashScreen()); // define it once at root level.
}
}
class SplashScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return SplashScreenState();
}
}
class SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 4), () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: Text(
'Welcome to BMI Calculator',
style: new TextStyle(
fontSize: 15.0, color: Colors.white, fontWeight: FontWeight.bold),
),
);
}
}
class HomePage extends StatelessWidget{
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'BMI Calculator',
style: new TextStyle(
color: Colors.white
),
),
),
);
}
}
The splash screen implementation is provided by default.
You just need to change the code in respective platforms like below
For Android:
Go to android directory in your flutter project and find the res folder where you will have launch_background.xml under drawables , just replace your own splash image as below.
`
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/white" />
<!-- You can insert your own image assets here -->
<item>
<bitmap
android:gravity="center"
android:src="#drawable/hotel_logo_new" />
</item>
</layer-list>
For iOS
- just change the LaunchImage under ImageAssets.
You should use pushReplacement instead of push when you exit the splash screen to prevent it from showing again when you press the back button.
here's the anmol.majhail code with the correct behavior.
import 'package:flutter/material.dart';
import 'package:bmi/HomePage.dart';
import 'dart:async';
main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: SplashScreen()); // define it once at root level.
}
}
class SplashScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return SplashScreenState();
}
}
class SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 4), () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: Text(
'Welcome to BMI Calculator',
style: new TextStyle(
fontSize: 15.0, color: Colors.white, fontWeight: FontWeight.bold),
),
);
}
}
class HomePage extends StatelessWidget{
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'BMI Calculator',
style: new TextStyle(
color: Colors.white
),
),
),
);
}
}
To use this package : add the dependency to your pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
splashscreen:
How to use
import 'package:flutter/material.dart';
import 'package:splashscreen/splashscreen.dart';
main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SplashScreen(
seconds: 10,
imageBackground: AssetImage('assets/images/a.jpg'),
navigateAfterSeconds: HomeScreen(),
),
); // define it once at root level.
}
}
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'Home',
style: new TextStyle(color: Colors.white),
),
),
);
}
}
Simple solution which i use in every app.
Use Timer class in build method code snippet
class SplashScreen extends StatefulWidget {
#override
Splash createState() => Splash();
}
class Splash extends State<SplashScreen> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
Timer(
Duration(seconds: 3),
() =>
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => LandingScreen())));
var assetsImage = new AssetImage(
'images/new_logo.png'); //<- Creates an object that fetches an image.
var image = new Image(
image: assetsImage,
height:300); //<- Creates a widget that displays an image.
return MaterialApp(
home: Scaffold(
/* appBar: AppBar(
title: Text("MyApp"),
backgroundColor:
Colors.blue, //<- background color to combine with the picture :-)
),*/
body: Container(
decoration: new BoxDecoration(color: Colors.white),
child: new Center(
child: image,
),
), //<- place where the image appears
),
);
}
}
I was looking for a way to check if the Snackbar has been dismissed, either by the user or by the timeout stuff. I could't really get any listener of doing it.
This is what I got so far,
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text("Title")))
.closed
.then((reason) {
// snackbar is now closed
});
This is the one way around, I was looking for exact listener. I don't want any work around, like setting duration of Snackbar and then listening to it after the duration has passed.
see full example below
I just wrapped SnackBar content with WillPopoScope and if the user pressed back button it will remove snackbar.
By default it will specify SnackBarClosedReason.remove reason
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: FirstPage(),
),
);
}
}
class FirstPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
child: Text('go to test page'),
onPressed: () => Navigator.of(context).push(MaterialPageRoute(builder: (context) => Test())),
),
);
}
}
class Test extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
child: Text('show snack'),
onPressed: () => _showSnack(context),
),
),
);
}
void _showSnack(BuildContext context) {
ScaffoldMessenger.of(context)
.showSnackBar(
SnackBar(
content: WillPopScope(
onWillPop: () async {
ScaffoldMessenger.of(context).removeCurrentSnackBar();
return true;
},
child: Text("Title"),
),
),
)
.closed
.then((reason) {
print('------------ $reason');
});
}
}
I am not sure how to generate multiple ListTiles by means of loops, such as for().
I do not know how Flutter works for rendering widgets, since in Angular 2 just insert the *ngFor directives in the layout (html).
I could not find such a subject in the Flutter documentation.
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: "Myapp",
home: new HomePage(),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) => new Scaffold(
appBar: new AppBar(
backgroundColor: new Color(0xFF26C6DA),
),
body: new ListView (
children: <Widget>[
new Card(
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: const Icon(Icons.album),
title: const Text('The Enchanted Nightingale'),
subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
),
],
),
),
],
)
);
}
List.generate() is useful for making small lists. For larger or infinite lists, use a ListView.builder() instead of ListView.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: "Myapp",
home: new HomePage(),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: new Color(0xFF26C6DA),
),
body: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Card(
child: const ListTile(
leading: const Icon(Icons.album),
title: const Text('The Enchanted Nightingale'),
subtitle: const Text(
'Music by Julie Gable. Lyrics by Sidney Stein.',
),
),
);
},
),
);
}
}
Here is the example with List.generate:-
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
title: "Myapp",
home: new HomePage(),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text('List.generate demo'),
),
body: new ListView(
padding: const EdgeInsets.all(8),
children: new List.generate(
10,
(index) => new ListTile(
title: Text('Item $index'),
),
),
),
);
}
}