How do I set the background color of my main screen in Flutter?
I'm learning Flutter, and I'm starting from the very basics. I'm not using MaterialApp. What's a good way to set the background color of the whole screen?
Here's what I have so far:
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new Center(child: new Text("Hello, World!"));
}
}
Some of my questions are:
- What's a basic way to set the background color?
- What exactly am I looking at, on the screen? Which code "is" the background? Is there a thing to set the background color on? If not, what's a simple and appropriate "simple background" (in order to paint a background color).
Thanks for the help!
The code above generates a black screen with white text:
You can set background color to All Scaffolds in application at once.
just set scaffoldBackgroundColor: in ThemeData
MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(scaffoldBackgroundColor: const Color(0xFFEFEFEF)),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
I think you can also use a scaffold to do the white background. Here's some piece of code that may help.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Testing',
home: new Scaffold(
//Here you can set what ever background color you need.
backgroundColor: Colors.white,
),
);
}
}
Hope this helps 😊.
Here's one way that I found to do it. I don't know if there are better ways, or what the trade-offs are.
Container "tries to be as big as possible", according to https://flutter.io/layout/. Also, Container can take a decoration
, which can be a BoxDecoration, which can have a color
(which, is the background color).
Here's a sample that does indeed fill the screen with red, and puts "Hello, World!" into the center:
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new Container(
decoration: new BoxDecoration(color: Colors.red),
child: new Center(
child: new Text("Hello, World!"),
),
);
}
}
Note, the Container is returned by the MyApp build(). The Container has a decoration and a child, which is the centered text.
See it in action here: