Подтвердить что ты не робот

Как установить цвет фона моего главного экрана в Flutter?

Я изучаю Флаттера, и я начинаю с самых оснований. Я не использую MaterialApp. Какой хороший способ установить цвет фона всего экрана?

Вот что у меня есть до сих пор:

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!"));
  }
}

Некоторые из моих вопросов:

  • Какой основной способ установить цвет фона?
  • На что именно я смотрю, на экране? Какой код "есть" фон? Есть ли способ установить цвет фона? Если нет, то какой простой и подходящий "простой фон" (чтобы нарисовать цвет фона).

Спасибо за помощь!

Приведенный выше код генерирует черный экран с белым текстом: enter image description here

4b9b3361

Ответ 1

Я думаю, вы также можете использовать эшафот, чтобы сделать белый фон. Вот некоторые части кода, которые могут помочь.

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,
        ),
      );
    }
}

Надеюсь, это поможет 😊.

Ответ 2

Вот один из способов, который я нашел для этого. Я не знаю, есть ли лучшие способы или какие компромиссы.

Контейнер "пытается быть как можно большим", согласно https://flutter.io/layout/. Кроме того, Контейнер может взять decoration, которое может быть BoxDecoration, которое может иметь color (который является цветом фона).

Здесь образец, который действительно заполняет экран красным, и помещает "Hello, World!". в центр:

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!"),
      ),
    );
  }
}

Примечание. Контейнер возвращается командой MyApp build(). В контейнере есть украшение и ребенок, который является центральным текстом.

Смотрите здесь в действии:

enter image description here

Ответ 3

На базовом примере Flutter вы можете установить с backgroundColor: Colors.X Scaffold

  @override
 Widget build(BuildContext context) {
   // This method is rerun every time setState is called, for instance as done
  // by the _incrementCounter method above.
   //
  // The Flutter framework has been optimized to make rerunning build methods
   // fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
  backgroundColor: Colors.blue,
  body: Center(
    // Center is a layout widget. It takes a single child and positions it
    // in the middle of the parent.
    child: Column(
      // Column is also layout widget. It takes a list of children and
      // arranges them vertically. By default, it sizes itself to fit its
      // children horizontally, and tries to be as tall as its parent.
      //
      // Invoke "debug painting" (press "p" in the console, choose the
      // "Toggle Debug Paint" action from the Flutter Inspector in Android
      // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
      // to see the wireframe for each widget.
      //
      // Column has various properties to control how it sizes itself and
      // how it positions its children. Here we use mainAxisAlignment to
      // center the children vertically; the main axis here is the vertical
      // axis because Columns are vertical (the cross axis would be
      // horizontal).
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          'You have pushed the button this many times:',
        ),
        Text(
          '$_counter',
          style: Theme.of(context).textTheme.display1,
        ),
      ],
    ),
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: _incrementCounter,
    tooltip: 'Increment',
    child: Icon(Icons.add_circle),
  ), // This trailing comma makes auto-formatting nicer for build methods.
);
}

Ответ 4

Есть много способов сделать это, я перечисляю несколько здесь.

  1. Использование backgroundColor

    Scaffold(
      backgroundColor: Colors.black,
      body: Center(...),
    )
    
  2. Использование Container в SizedBox.expand

    Scaffold(
      body: SizedBox.expand(
        child: Container(
          color: Colors.black,
          child: Center(...)
        ),
      ),
    )
    
  3. Использование Theme

    Theme(
      data: Theme.of(context).copyWith(scaffoldBackgroundColor: Colors.black),
      child: Scaffold(
        body: Center(...),
      ),
    )
    

Ответ 5

Вы можете установить цвет фона для всех лесов сразу в приложении.

просто установите scaffoldBackgroundColor: в ThemeData

 MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(scaffoldBackgroundColor: const Color(0xFFEFEFEF)),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );

Ответ 6

Я думаю, вам нужно использовать виджет MaterialApp и использовать theme и установить primarySwatch с цветом, который вы хотите. выглядят как ниже код,

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 MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

Ответ 7

и это другой подход к изменению цвета фона:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(backgroundColor: Colors.pink,),);
  }
}

Ответ 8

Scaffold(
      backgroundColor: Constants.defaulBackground,
      body: new Container(
      child: Center(yourtext)

      )
)