Flutter 封装Text 点击事件(纯点击、路由)

新手学习note,如有不对,还请指出,谢谢!

TODO
还应该加入Text style、居中 等等

首先,增加空判断的Text

import 'package:flutter/widgets.dart';

class NonNullText extends Text {
  NonNullText(String data) : super(data == Null ? '' : data);
}
  • 单纯点击
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'NonNullText.dart';

class ClickableText extends Container {
  String text;
  VoidCallback onClick;

  ClickableText({this.text, this.onClick});

  @override
  Widget build(BuildContext context) {
    String text = this.text;

    VoidCallback onClick = this.onClick;
    if (onClick == Null) {
      onClick = () {};
    }

    return new Container(
      alignment: Alignment.center,
      padding: EdgeInsets.all(10.0),
      child: GestureDetector(
        child: NonNullText(text),
        onTap: onClick,
      ),
    );
  }
}

使用方法,传入text 和 点击事件。

  • 点击跳转到下一页面
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutterapp/ui/view/ClickableText.dart';

class RouteText extends ClickableText {
  String text;
  BuildContext context;

  RouteText({this.context, this.text, Widget widget})
      : super(
            text: text,
            onClick: () {
              Navigator.push(
                context,
                new MaterialPageRoute(builder: (context) => widget),
              );
            });
}

使用方法

new RouteText(
        context: context,
        text: name,
        widget: new WeaponDetail(weapon.id, name));//下一页

你可能感兴趣的:(Flutter 封装Text 点击事件(纯点击、路由))