Flutter Force State 具有一定的 Mixin

问题描述 投票:0回答:2

我有一个混合(

MyMixin
),我在一些小部件的状态下应用它,如下所示:

    class MyStfulWidget extends StatefulWidget {
      @override
      _MyStfulWidget State createState() => _MyStfulWidget State();
    }
    
    class _MyStfulWidget State extends State<MyStfulWidget> with MyMixin { ... }

我有时需要将此有状态小部件作为方法的参数传递(

MyMethod

    void myMethod(Widget myWidget) { ... }

以下方法的问题在于它接受各种小部件。如果我传递一个没有 MyMixin 的小部件,它将无法正常工作......

有什么方法可以强制“myWidget”参数成为一个在其状态中包含 mixin 的有状态小部件吗?

感谢您的帮助!

flutter dart mixins
2个回答
1
投票

试试这个代码:

import 'package:flutter/material.dart';

void main() {
  myMethod(Widget1());
  myMethod(Widget2());
}

void myMethod(StatefulWidget myWidget) {
  final state = myWidget.createElement().state;
  if (state is MyMixin) {
    print('Hey! $myWidget is MyMixin');
  } else {
    print('Hey! $myWidget bypassed');
  }
}
class Widget1 extends StatefulWidget {
  Widget1({super.key});

  @override
  State<Widget1> createState() => _Widget1State();
}

class _Widget1State extends State<Widget1> with MyMixin {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class Widget2 extends StatefulWidget {
  Widget2({super.key});

  @override
  State<Widget2> createState() => _Widget2State();
}

class _Widget2State extends State<Widget2> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

mixin MyMixin<T extends StatefulWidget> on State<T> {}

0
投票

我最终实现这一目标的方法是创建一个新的抽象类

MyMixinWidget
,它扩展了一个Stateful Widget,这反过来又迫使
createState()
返回一个新的抽象类
MyMixinState
,它用
MyMixin
扩展了State。

abstract class MyMixinWidget extends StatefulWidget {
  const MyMixinWidget({Key? key}) : super(key: key);

  @override
  MyMixinState createState();
}

abstract class MyMixinState<T extends MyMixinWidget> extends State<T> with MyMixin {
}

所以可以这样实现

class MyWidget extends MyMixinWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  MyMixinState<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends MyMixinState<MyWidget> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.