如何使此应用程序中的列表视图项目在点击时添加到历史记录页面?

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

我正在尝试构建一个 Flutter 应用程序,在主屏幕上有一个列表视图生成器,但我也希望有一个历史记录页面,用户可以在其中查看他们查看过的页面。我无法使我的历史页面正常工作,因此我创建了代码示例并获取反馈。

PS:我没有编程背景,这样做只是为了享受。这也将是我的第一个项目,所以我不知道制作历史页面是否需要大量编码,或者我正在做的就是这么简单。

注意:在下面的代码中,列表视图中的项目有时会消失。要让它们回来,只需点击文本字段中的 X。

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

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

final routes = RouteMap(
  routes: {
    '/': (_) => CupertinoTabPage(
          child: HomePage(),
          paths: const ['/scientists', '/settings'],
        ),
    '/scientists': (_) =>
        const MaterialPage(child: ScientistsBiographyScreen()),
    // '/settings': (_) => MaterialPage(child: HistoryScreen()),
  },
);

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerDelegate: RoutemasterDelegate(routesBuilder: (_) => routes),
      routeInformationParser: const RoutemasterParser(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final tabState = CupertinoTabPage.of(context);

    return ScientistsBiographyScreen();
  }
}

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

  @override
  State<ScientistsBiographyScreen> createState() =>
      _ScientistsBiographyScreenState();
}

class _ScientistsBiographyScreenState extends State<ScientistsBiographyScreen> {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
  final List<String> allscientistsBiography = [
    "einstein",
    "tesla",
    "einstein",
    "tesla",
    "einstein",
    "tesla",
    "einstein",
    "tesla",
    "einstein",
    "tesla",
    "einstein",
    "tesla",
    "einstein",
    "tesla",
    "einstein",
    "tesla",
    "einstein",
    "tesla",
  ];

  List<String> filteredScientists = [];
  final TextEditingController _searchController = TextEditingController();
  final List<String> tappedScientists = [];

  void filterScientists(String query) {
    setState(() {
      filteredScientists = allscientistsBiography
          .where((scientist) =>
              scientist.toLowerCase().contains(query.toLowerCase()))
          .toList();
    });
  }

  void clearSearch() {
    _searchController.clear();
    filterScientists('');
  }

  void showHistoryScreen() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => HistoryScreen(tappedScientists)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const ScientistsAppbar(),
      key: scaffoldKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Directionality(
            textDirection:
                TextDirection.ltr, // Set the text direction to right-to-left
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: SizedBox(
                height: 60,
                child: TextField(
                  controller: _searchController,
                  onChanged: filterScientists,
                  decoration: InputDecoration(
                    labelText: 'Search here',
                    prefixIcon: const Icon(Icons.search),
                    suffixIcon: IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: clearSearch,
                    ),
                    border: const OutlineInputBorder(),
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: Directionality(
              textDirection:
                  TextDirection.ltr, // Set the text direction to right-to-left
              child: ScientistsBiography(
                scientists: filteredScientists,
                onTapScientist: (scientistsBiography) {
                  setState(() {
                    tappedScientists.add(scientistsBiography);
                  });
                  if (scientistsBiography == "einstein") {
                    Routemaster.of(context).push('/scientists-einstein');
                  }
                  if (scientistsBiography == "tesla") {
                    Routemaster.of(context).push('/scientists-tesla');
                  }
                },
              ),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: showHistoryScreen,
        child: const Icon(Icons.history),
      ),
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }
}

class HistoryScreen extends StatelessWidget {
  final List<String> tappedScientists;
  const HistoryScreen(this.tappedScientists, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('History'),
      ),
      body: ListView.builder(
        itemCount: tappedScientists.length,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            title: Text(tappedScientists[index]),
          );
        },
      ),
    );
  }
}

class ScientistsBiography extends StatelessWidget {
  final List<String> scientists;
  final Function(String) onTapScientist;

  const ScientistsBiography({
    Key? key,
    required this.scientists,
    required this.onTapScientist,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: scientists.length,
      itemBuilder: (BuildContext context, int index) {
        return ListTileScientists(
          scientistsBiography: scientists[index],
          onTap: () {
            onTapScientist(scientists[index]);
          },
        );
      },
    );
  }
}

class ListTileScientists extends StatelessWidget {
  final String scientistsBiography;
  final VoidCallback? onTap;

  const ListTileScientists({
    Key? key,
    required this.scientistsBiography,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: ListTile(
        key: key,
        title: Text(scientistsBiography),
        trailing: const Icon(Icons.arrow_forward),
      ),
    );
  }
}

class CardButton extends StatelessWidget {
  final String label;
  final VoidCallback? onPressed;

  const CardButton({
    Key? key,
    required this.label,
    this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 50,
      child: Card(
        child: InkWell(
          onTap: onPressed,
          child: Center(
            child: Text(
              label,
              style: const TextStyle(fontSize: 16),
            ),
          ),
        ),
      ),
    );
  }
}

class ScientistsAppbar extends StatelessWidget implements PreferredSizeWidget {
  const ScientistsAppbar({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      // centerTitle: true,
      title: ShaderMask(
        shaderCallback: (Rect bounds) {
          return const LinearGradient(
            colors: [
              Color.fromARGB(255, 142, 154, 215),
              Color.fromARGB(255, 219, 84, 84)
            ], // Define your gradient colors here
            tileMode: TileMode.clamp,
          ).createShader(bounds);
        },
        child: const Text(
          'Scientists',
          style: TextStyle(
            fontSize: 24.0, // Adjust font size as needed
            fontWeight: FontWeight.bold, // Adjust font weight as needed
            color: Colors.white, // Text color (will be masked by the gradient)
          ),
        ),
      ),
      leading: IconButton(
        icon: const Icon(Icons.history),
        onPressed: () {
          Routemaster.of(context).pop();
        },
      ),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}

class ScientistsAppbarStyle extends StatelessWidget {
  const ScientistsAppbarStyle({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return ShaderMask(
      shaderCallback: (Rect bounds) {
        return const LinearGradient(
          colors: [
            Color.fromARGB(255, 255, 255, 255),
            Color.fromARGB(255, 111, 84, 219)
          ], // Define your gradient colors here
          tileMode: TileMode.clamp,
        ).createShader(bounds);
      },
      child: const Text(
        'Scientists',
        style: TextStyle(
          fontSize: 24.0, // Adjust font size as needed
          fontWeight: FontWeight.bold, // Adjust font weight as needed
          color: Colors.white, // Text color (will be masked by the gradient)
        ),
      ),
    );
  }
}
android flutter dart android-listview routemaster
1个回答
0
投票

我运行了你的代码,但当我按下浮动按钮时,历史记录页面似乎工作得很好。 如果您指的是应用程序栏上的历史记录按钮(页面标题“科学家”旁边),那么解决方案如下:

将点击的Scientists发送到ScientistsAppbar类。

Widget build(BuildContext context) {
return Scaffold(
  appBar: ScientistsAppbar(tappedScientists: tappedScientists),
  key: scaffoldKey,
  body: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: [
      Directionality(
        textDirection:

然后从ScientistsAppbar类中调用tappedScientists。

class ScientistsAppbar extends StatelessWidget implements 
 PreferredSizeWidget {
  final List<String> tappedScientists;
  const ScientistsAppbar({required this.tappedScientists, Key? key})
   : super(key: key);

在同一个类中为onpressed提供到历史页面的路由

leading: IconButton(
    icon: const Icon(Icons.history),
    onPressed: () {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => HistoryScreen(tappedScientists)),
      );
    },
  ),
© www.soinside.com 2019 - 2024. All rights reserved.