Флаттер: где я могу добавить текст () - PullRequest
0 голосов
/ 09 марта 2020

Я хочу коснуться экрана и изменить цвет фона на случайный. Он работает нормально, но я хочу добавить текст в центре экрана, помогите мне, пожалуйста. Может быть, у кого-то есть идеи, спасибо! Я пытаюсь добавить несколько дочерних в AnimatedContainer. Попытка добавить текст в GestureDetector, но он не работает правильно

TopScreen.dart

import 'package:flutter/material.dart';

class TopScreen extends StatefulWidget {
  final Widget child; //child widget

  TopScreen({this.child});

  @override
  State createState() => _TopScreenState();

  static _TopScreenState of (BuildContext context) {
    assert(context != null);
    final _TopScreenState result = context.findAncestorStateOfType();
    return result;
  }
}

class _TopScreenState extends State<TopScreen> {
  Color _color = Colors.white;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: AnimatedContainer(
          child: widget.child,
          color: _color,
          duration: Duration(milliseconds: 500),
        ),
    );
  }

  void setColor(Color color) {
    this._color = color;
  }
}

main.dart

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:solidsoftwaretest/TopScreen.dart';

void main() => runApp(MaterialApp(home: TopScreen(child: MainScreen())));

class MainScreen extends StatefulWidget {
  @override
  State createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
            onTap: () {
              TopScreen.of(context).setColor(Colors.primaries[Random().nextInt(Colors.primaries.length)]);
              TopScreen.of(context).setState(() {});
            },

    );
  } //build
}

UPD: если я добавлю Child (Текст) в GestureDetector - gestDetector работает только с текстом.

class _MainScreenState extends State<MainScreen> {

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Center(
        child: Text('Hey there!')
      ),
        onTap: () {
          TopScreen.of(context).setColor(Colors.primaries[Random().nextInt(Colors.primaries.length)]);
          TopScreen.of(context).setState(() {});
        }
    );
  } //build
}

Ответы [ 2 ]

5 голосов
/ 09 марта 2020

Вы можете добавить Text виджет внутри Container и обернуть его дальше в GestureDetector. Чтобы заставить GestureDetector работать на всей области, выделите Container прозрачный цвет следующим образом:

return GestureDetector(
  onTap: () {
    TopScreen.of(context).setColor(Colors.primaries[Random().nextInt(Colors.primaries.length)]);
      TopScreen.of(context).setState(() {});
  },
  child: Container(
    color: Colors.transparent,
    alignment: Alignment.center,
    child: Text('Hey there'),
    ),
  );

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

0 голосов
/ 09 марта 2020

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

ScaffoldColorCenterText60597839(
  child: Text('Bananas'),
)

class ScaffoldColorCenterText60597839 extends StatefulWidget {
  final Widget child;
  ScaffoldColorCenterText60597839({
    this.child
  });

  @override
  _ScaffoldColorCenterText60597839State createState() => _ScaffoldColorCenterText60597839State();
}

class _ScaffoldColorCenterText60597839State extends State<ScaffoldColorCenterText60597839> {
  Color _color = Colors.white;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnimatedContainer(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              widget.child,
              Text('A text widget')
            ],
          )
        ),
        color: _color,
        duration: Duration(milliseconds: 500),
      ),
    );
  }
}
...