我只能使Flutter中的iPad仅使GridView的一个元素消失吗?

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

仅当设备是iPad时,我才想在gridView中隐藏元素。我曾尝试检索DeviceInfo,但由于我的GridView返回了一个以gridView元素作为其子元素的GestureDetetctor,因此我不知道如何隐藏它。我虽然将不透明度设为零,但是我不知道如何实现,因为返回的所有内容都包装在一个gestureDetector中。

Expanded(
                          flex: 18,
                          child: GridView.builder(
                            itemCount: homeList.length,
                            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 2, mainAxisSpacing: 20),
                            itemBuilder: (ctx, i) {
                              return GestureDetector(
                                onTap: () {
                                  if (i == 0) {
                                    _interstitialAd.show();
                                  } else if (i == 1) {

                                  } else if (i == 2) {
                                    sendInvite();
                                  } else if (i == 3) {
                                    hideBannerAd();
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => Null()));
                                  } else if (i == 4) {
                                    hideBannerAd();
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => Main()));
                                  } else if (i == 5) {
                                    hideBannerAd();
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) => Body()));
                                  }
                                },
                                child: Container(
                                  decoration: BoxDecoration(
                                    borderRadius: const BorderRadius.all(
                                        Radius.circular(16.0)),
                                  ),
                                  width: 150,
                                  margin:
                                      const EdgeInsets.symmetric(horizontal: 11.0),
                                  child: Container(
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.circular(19.0),
                                      child: Stack(
                                        children: <Widget>[
                                          Positioned.fill(
                                            child: Image.asset(
                                              homeList[i].imagePath,
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                          Positioned(
                                            bottom: 0,
                                            left: 0,
                                            right: 0,
                                            child: Container(
                                              padding: EdgeInsets.symmetric(
                                                  horizontal: 9.0, vertical: 5.0),
                                              decoration: BoxDecoration(
                                                  gradient: LinearGradient(
                                                    colors: [
                                                      const Color(0xFFFF8C3B),
                                                      const Color(0xFFFE524B)
                                                    ],
                                                    begin: Alignment.centerLeft,
                                                    end: Alignment.centerRight,
                                                  ),
                                                  borderRadius: BorderRadius.only(
                                                      topRight:
                                                          Radius.circular(15))),
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: <Widget>[
                                                  Text(
                                                    "${homeList[i].taskTitle}",
                                                    style: TextStyle(
                                                      fontFamily: "Netflix",
                                                      fontWeight: FontWeight.w600,
                                                      fontSize: 17,
                                                      letterSpacing: 0.27,
                                                      color: Colors.white,
                                                    ),
                                                  ),

这是我的gridView的样子:enter image description here

更新:我尝试了这个,但是似乎没有用

 iPad async(){
// checks for device iPad  
}
return Visibility(
                            visible: iPad,
                            child: GestureDetector(
                              onTap: () async {
                                if (i == 0) {
                                  if (await interstitialAd.isLoaded) {
                                    interstitialAd.show();
                                  } else {
                                  Reward(context);
                                  }
                                } else if (i == 1) {

                                } else if (i == 2) {
                                  sendInvite();
                                } else if (i == 3) {
                                  hideBannerAd();
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => Scratch()));
                                }= else if (i == 5 && _isVisible()) {
                                  hideBannerAd();
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => Body()));
                                }
user-interface flutter gridview dart user-experience
1个回答
0
投票

您可以在下面复制粘贴运行完整的示例代码步骤1:使用2个预定义列表allListnoIpadList,在检查设备类型之后,使homeList指向allListnoIpadList

static List<Home> noIpadList = [
    Home(taskTitle: "a", imagePath: "a", routeName: "/a"),
    Home(taskTitle: "b", imagePath: "b", routeName: "/b")
  ];

  static List<Home> allList = List.from(noIpadList)
    ..add(Home(taskTitle: "ipad", imagePath: "ipad", routeName: "/ipad"));

  List<Home> homeList;

    super.initState();
    if (isIpad) {
      homeList = noIpadList;
    } else {
      homeList = allList;
    }
  }

步骤2:使用route简化push动作,并且当ontap选中homeList[i].taskTitle而不是index时,因为ipad项目可能不存在

return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      routes: {         
        '/': (context) => MyHomePage(title: 'Flutter Demo Home Page'),          
        '/a': (context) => Main(),
        '/b': (context) => Body(),
        '/ipad': (context) => Body(),
      },

return GestureDetector(
              onTap: () {
               if (widget.homeList[i].taskTitle == "a") {
                 Navigator.pushNamed(context, widget.homeList[i].routeName);
               }
               if (widget.homeList[i].taskTitle == "b") {
                 Navigator.pushNamed(context, widget.homeList[i].routeName);
               }
               if (widget.homeList[i].taskTitle == "ipad") {
                 Navigator.pushNamed(context, widget.homeList[i].routeName);
               }

工作演示更改checkIsIpad()返回truefalse您可以看到ipad项目显示或消失

enter image description here

完整示例代码

import 'package:flutter/material.dart';
import 'package:device_info/device_info.dart';

Future<bool> checkIsIpad() async {
  /*DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  IosDeviceInfo info = await deviceInfo.iosInfo;
  if (info.name.toLowerCase().contains("ipad")) {
    return true;
  }
  return false;*/
  return true;
}

bool isIpad = false;
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  isIpad = await checkIsIpad();
  runApp(MyApp());
}

class Home {
  String taskTitle;
  String imagePath;
  String routeName;

  Home({this.taskTitle, this.imagePath, this.routeName});
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      routes: {
        // When navigating to the "/" route, build the FirstScreen widget.
        '/': (context) => MyHomePage(title: 'Flutter Demo Home Page'),
        // When navigating to the "/second" route, build the SecondScreen widget.
        '/a': (context) => Main(),
        '/b': (context) => Body(),
        '/ipad': (context) => Body(),
      },
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  static List<Home> noIpadList = [
    Home(taskTitle: "a", imagePath: "a", routeName: "/a"),
    Home(taskTitle: "b", imagePath: "b", routeName: "/b")
  ];

  static List<Home> allList = List.from(noIpadList)
    ..add(Home(taskTitle: "ipad", imagePath: "ipad", routeName: "/ipad"));

  List<Home> homeList;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (isIpad) {
      homeList = noIpadList;
    } else {
      homeList = allList;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(flex: 1, child: Test(homeList: homeList)),
            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),
      ),
    );
  }
}

class Test extends StatefulWidget {
  final List<Home> homeList;

  Test({this.homeList});
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
    return GridView.builder(
        itemCount: widget.homeList.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2, mainAxisSpacing: 20),
        itemBuilder: (ctx, i) {
          return GestureDetector(
              onTap: () {
               if (widget.homeList[i].taskTitle == "a") {
                 Navigator.pushNamed(context, widget.homeList[i].routeName);
               }
               if (widget.homeList[i].taskTitle == "b") {
                 Navigator.pushNamed(context, widget.homeList[i].routeName);
               }
               if (widget.homeList[i].taskTitle == "ipad") {
                 Navigator.pushNamed(context, widget.homeList[i].routeName);
               }

              },
              child: Container(
                  decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(16.0)),
                  ),
                  width: 150,
                  margin: const EdgeInsets.symmetric(horizontal: 11.0),
                  child: Container(
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(19.0),
                          child: Stack(children: <Widget>[
                            Positioned.fill(
                              child: Image.asset(
                                widget.homeList[i].imagePath,
                                fit: BoxFit.cover,
                              ),
                            ),
                            Positioned(
                                bottom: 0,
                                left: 0,
                                right: 0,
                                child: Container(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 9.0, vertical: 5.0),
                                    decoration: BoxDecoration(
                                        gradient: LinearGradient(
                                          colors: [
                                            const Color(0xFFFF8C3B),
                                            const Color(0xFFFE524B)
                                          ],
                                          begin: Alignment.centerLeft,
                                          end: Alignment.centerRight,
                                        ),
                                        borderRadius: BorderRadius.only(
                                            topRight: Radius.circular(15))),
                                    child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Text(
                                            "${widget.homeList[i].taskTitle}",
                                            style: TextStyle(
                                              fontFamily: "Netflix",
                                              fontWeight: FontWeight.w600,
                                              fontSize: 17,
                                              letterSpacing: 0.27,
                                              color: Colors.white,
                                            ),
                                          ),
                                        ])))
                          ])))));
        });
  }
}

class Main extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text("Main");
  }
}

class Body extends StatefulWidget {
  @override
  _BodyState createState() => _BodyState();
}

class _BodyState extends State<Body> {
  @override
  Widget build(BuildContext context) {
    return Text("Body");
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.