Как установить обратный отсчет таймера во флаттере на 30 секунд с кнопкой FAB OnPressed?

Да, есть простой и понятный способ сделать это.

Вызов «axhline» и «axvline» из экземпляра оси - это метод, одобренный в документации MPL.

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

Так, например, этот код создаст сюжет и покрасит x- ось зеленая и увеличить ширину линии по оси x от значения по умолчанию «1» до значения «4»; ось y окрашена в красный цвет, а ширина линии оси y увеличена с «1» до «8».

from matplotlib import pyplot as PLT
fig = PLT.figure()
ax1 = fig.add_subplot(111)

ax1.axhline(linewidth=4, color="g")        # inc. width of x-axis and color it green
ax1.axvline(linewidth=4, color="r")        # inc. width of y-axis and color it red

PLT.show()

Функция axhline / axvline принимает дополнительные аргументы, которые должны позволять вам сделайте все, что бы вы ни хотели эстетически, в частности, любой из свойств matplotlib.lines.Line2D являются допустимыми kwargs (например, «альфа», «linestyle», capstyle, joinstyle).

0
задан fluttertalk 20 March 2019 в 12:49
поделиться

2 ответа

попробуйте следующее:

import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:async';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Counter App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Counter App'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  int _counter = 0;
  AnimationController controller;

  Duration get duration => controller.duration * controller.value;

  bool get expired => duration.inSeconds == 0;

  @override
  void initState() {
    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 20),
    );

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            AnimatedBuilder(
              animation: controller,
            builder: (BuildContext context, Widget child) {
              return new Text(
                '${duration.inSeconds}',
                style: new TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 50.0,
                ),
              );
            }),
            new Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                new RaisedButton(
                  padding: const EdgeInsets.all(15.0),
                  textColor: Colors.white,
                  color: Colors.redAccent,
                  onPressed: () {
                    setState(() {
                      controller.reset();
                    });
                  },
                  child: new Text("Reset"),
                ),
              ],
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Container(
          height: 50.0,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => setState(() {

          controller.reverse(from: 1);
            }),
        tooltip: 'Increment Counter',
        child: Icon(Icons.add),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }
}
0
ответ дан Sami Kanafani 20 March 2019 в 12:49
поделиться

Вы можете использовать этот код в любом месте.

Timer(Duration(seconds: 30), () {
      //checkFirstSeen(); your logic
    });
0
ответ дан Bhanuka Isuru 20 March 2019 в 12:49
поделиться
Другие вопросы по тегам:

Похожие вопросы: